﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;
//using Module_Debug.Hardware;

namespace Module_Debug
{
    public partial class ILI7838_644 : Form
    {
        List<string> lines;
        /// <summary>
        /// ///ILI7838_644  
        /// </summary>

        private bool Listening = false;//是否没有执行完invoke相关操作   
        //private bool IClosing = false;//是否正在关闭串口，执行Application.DoEvents，并阻止再次invoke  
        //==============ca310===============        
        private double auto_lum;//
        private double auto_x;
        private double auto_y;

        /// <summary>
        /// /auto gamma add 20181031
        /// </summary>
        private int flag1 = 1;
        private int flag2 = 1;
        private int flag3 = 1;

        private int CAS200_Measure_Gray = 255;
        private List<byte> buffer = new List<byte>(2048);//默认分配1/16页内存，并始终限制不允许超过   
        private byte[] Rec_tmp = new byte[1];//
        private byte[] Rec_tmp1 = new byte[1];//
        private byte[] Send_buf = new byte[1];
        private byte signal_mode;
        public byte start_trans_flag = 0;
        public byte continueflag = 0;

        public byte Seil_port_Find_flag = 0;
        //private byte[] Driver_IC = new byte[1];
        //private List<string> ImageType;
        private delegate void MonitorSerialPortChangeEventHandler();

        public static bool firstGammaFlag = true;
        CRC16 CRCData = new CRC16();
        frmMain MainForm = null;
        public ILI7838_644(frmMain Frm)
        {
            MainForm = Frm;
            InitializeComponent();
            MainForm.Child_window_hide_already = true;
            MainForm.Child_Gamma_Window_Open_Enable = false;//防止重复开启子窗体  
        }
        private void Frm_Activated(object sender, EventArgs e)
        {
            if ((MainForm.btnCal_manual.Tag != null) && (Convert.ToString(MainForm.btnCal_manual.Tag) != "0calerr"))
            {
                btnAutoGammas_VTDR6100.Enabled = true;
                txttip.Text += "AutoGamma Enabled." + "\r\n";
            }
        }
        //=================================Timer====Start=========================
        private void T1_Tick(object sender, EventArgs e)
        {
            T1.Enabled = false;
            txttip.Text = txttip.Text + "通讯故障!\r\n";
            txttip.Focus();//获取焦点
            txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
            txttip.ScrollToCaret();//滚动到光标处
        }
        private void T2_Tick(object sender, EventArgs e)
        {
            toolStripStatusLabel2.Text = DateTime.Now.ToString();
        }
        //=================================Timer====end=========================
        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            //if (MainForm.IClosing) return;
            try
            {
                Listening = true;//设置标记，说明我已经开始处理数据，一会儿要使用系统UI的。         
                int n = MainForm.comPort.BytesToRead;
                byte[] buf = new byte[n];
                byte data;
                Setting.TempRecord.cmdLen = n;
                MainForm.comPort.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                byte CRCH, CRCL;
                if (buffer.Count > 3)
                {
                    if (buffer[0] == 0x0B)          //返回 STM32内部 flash 的配置文件数据
                    {
                        if (buffer.Count >= (Int16)(buffer[2] << 8) + (buffer[3]) + 7)
                        {
                            Rec_tmp = new byte[(Int16)(buffer[2] << 8) + (buffer[3]) + 7];
                            byte[] crcTemp = new byte[(Int16)(buffer[2] << 8) + (buffer[3]) + 7];
                            buffer.CopyTo(0, crcTemp, 0, (Int16)(buffer[2] << 8) + (buffer[3]) + 7);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[(Int16)(buffer[2] << 8) + (buffer[3]) + 7 - 2] != CRCH && buffer[(Int16)(buffer[2] << 8) + (buffer[3]) + 7 - 1] != CRCL) //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, (Int16)(buffer[2] << 8) + (buffer[3]) + 7);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, (Int16)(buffer[2] << 8) + (buffer[3]) + 7);//正确分析一条数据，从缓存中移除数据。
                            }

                        }
                    }
                    else if (((buffer[0] == 0x99) || (buffer[0] == 0x9F)) && (Setting.TempRecord.cmdLen > 0))
                    {

                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, buffer.Count);  //正确分析一条数据，从缓存中移除数据。  
                            }
                        }
                    }
                    else if (buffer[0] == 0xFE)
                    {
                        Rec_tmp = new byte[buffer[2] + 5];
                        byte[] crcTemp = new byte[buffer[2] + 5];
                        buffer.CopyTo(0, crcTemp, 0, buffer[2] + 5);

                        CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                        if (buffer[buffer[2] + 5 - 2] != CRCH && buffer[buffer[2] + 5 - 1] != CRCL)     //CRC校验出错
                        {
                            buffer.RemoveRange(0, buffer.Count);
                        }
                        else
                        {
                            buffer.CopyTo(0, Rec_tmp, 0, buffer[2] + 5);//复制一条完整数据到具体的数据缓存   
                            data_1_catched = true;
                            buffer.RemoveRange(0, buffer[2] + 5);//正确分析一条数据，从缓存中移除数据。
                            if (Rec_tmp[4] == 0)
                                continueflag = 1;
                        }
                    }
                    else if (buffer[0] == 0x55)     //STM32 更新bin文件成功  返回
                    {
                        if (buffer.Count >= (buffer[2] + 5))
                        {
                            Rec_tmp = new byte[(buffer[2] + 5)];
                            byte[] crcTemp = new byte[(buffer[2] + 5)];
                            buffer.CopyTo(0, crcTemp, 0, (buffer[2] + 5));

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[(buffer[2] + 5) - 2] != CRCH && buffer[(buffer[2] + 5) - 1] != CRCL)       //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, (buffer[2] + 5));//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, (buffer[2] + 5));//正确分析一条数据，从缓存中移除数据。
                                switch (Rec_tmp[3])
                                {
                                    case 0x00:
                                        {
                                            start_trans_flag = 1;
                                        }
                                        break;
                                    case 0x01:
                                        {
                                            if (MainForm.comPort.IsOpen == true) MainForm.comPort.Close();
                                        }
                                        break;
                                    case 0x02:
                                        {
                                            start_trans_flag = 0;
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }

                        }
                    }
                    else if (((buffer[0] == 0x1E) || (buffer[0] == 0x0E) || (buffer[0] == 0x0D) || (buffer[0] == 0x0A) || (buffer[0] == 0x09) || (buffer[0] == 0x08) || (buffer[0] == 0x19) || (buffer[0] == 0x29) || (buffer[0] == 0x2A) || (buffer[0] == 0x09) || (buffer[0] == 0x2E) || (buffer[0] == 0x2B) || (buffer[0] == 0x2C) || (buffer[0] == 0x2D) || (buffer[0] == 0x2F) || (buffer[0] == 0x30) || (buffer[0] == 0x31) || (buffer[0] == 0x3C) || (buffer[0] == 0x3D) || (buffer[0] == 0x4A)
                        || (buffer[0] == 0x4C) || (buffer[0] == 0x52)) || (buffer[0] == 0x6F) || (buffer[0] == 0x53) && (Setting.TempRecord.cmdLen > 0))
                    {
                        if (buffer.Count >= Setting.TempRecord.cmdLen)
                        {
                            Rec_tmp = new byte[Setting.TempRecord.cmdLen];
                            byte[] crcTemp = new byte[Setting.TempRecord.cmdLen];
                            buffer.CopyTo(0, crcTemp, 0, Setting.TempRecord.cmdLen);

                            CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                            if (buffer[Setting.TempRecord.cmdLen - 2] != CRCH && buffer[Setting.TempRecord.cmdLen - 1] != CRCL)     //CRC校验出错
                            {
                                buffer.RemoveRange(0, buffer.Count);
                            }
                            else
                            {
                                buffer.CopyTo(0, Rec_tmp, 0, Setting.TempRecord.cmdLen);//复制一条完整数据到具体的数据缓存   
                                data_1_catched = true;
                                buffer.RemoveRange(0, Setting.TempRecord.cmdLen);//正确分析一条数据，从缓存中移除数据。 
                            }
                        }
                    }
                    else
                        buffer.RemoveRange(0, buffer.Count);
                }
                if (data_1_catched)
                {
                    this.Invoke((EventHandler)(delegate
                    {
                        T1.Enabled = false; //停止超时计数

                        //------------------------------------------------------------------------------------------------------------------------

                        ////---------------------------------------------------RM67160/RM67162/RM69310---------------------------------------
                        if ((Rec_tmp[0] == 0x0E) || (Rec_tmp[0] == 0x1E) || (Rec_tmp[0] == 0x52))  //RM67160/RM67162/RM69310
                        {
                            string tmp = "";
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            txttip.Text = txttip.Text + "寄存器\t写 OK！\r\n";
                                    }
                                    break;

                                case 0x02:
                                    {

                                        {

                                            tmp = String.Format("{0:X2}", Rec_tmp[4]);//16进制
                                            //ILI7838_644_txtRegData.Text = tmp;
                                            txttip.Text = txttip.Text + "寄存器\t读 OK！\r\n";
                                        }
                                    }
                                    break;
                                case 0x03://///write gamma ok  RM69310
                                    txttip.Text = txttip.Text + "寄gamma存器\t写 OK！\r\n";
                                    break;

                                case 0x04://///read gamma ok  RM69310
                                    {
                                        txttip.Text = txttip.Text + "读gamma寄存器\t 读 OK！\r\n";
                                    }
                                    break;

                                case 0x05://///write otp ok  RM69310
                                    txttip.Text = txttip.Text + "OTP  \t  写 OK！\r\n";
                                    break;

                                case 0x06://///read otp ok  RM69310
                                    txttip.Text = txttip.Text + "OTP  \t  Read OK！\r\n";

                                    tmp = String.Format("{0:X2}", Rec_tmp[3]);//16进制


                                    break;
                            }
                        }
                        else if (Rec_tmp[0] == 0x53)//////ILI7838_644用的。
                        {
                            string tmp = "";
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            txttip.Text = txttip.Text + "寄存器\t写 OK！\r\n";
                                    }
                                    break;

                                case 0x02:
                                    {

                                        {

                                            for (int i = 3; i < (Rec_tmp[2] + 2); i++)
                                            {
                                                tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                            }


                                            //ILI7838_644_txtRegData.Text = tmp;
                                            txttip.Text = txttip.Text + "寄存器\t读 OK！\r\n";
                                        }
                                    }
                                    break;

                                case 0x03://///write gamma ok  RM69310
                                    txttip.Text = txttip.Text + "寄gamma存器\t写 OK！\r\n";
                                    break;

                                case 0x05://///write otp ok  RM69310
                                    txttip.Text = txttip.Text + "OTP  \t  写 OK！\r\n";
                                    break;

                                default:
                                    {

                                    }
                                    break;
                            }
                        }
                        else if (Rec_tmp[0] == 0x6F)
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01: { if (Rec_tmp[4] == 0x00) MainForm.textBox1.Text = MainForm.textBox1.Text + "写寄存器\tOK！\r\n"; } break;//寄存器写功能返回状态
                                case 0x02:
                                    {
                                        int i;
                                        string tmp = "";
                                        for (i = 3; i <= (Rec_tmp[2] + 1); i++)
                                        {
                                            tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                        }
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]);

                                        //ILI7838_644_txtRegData.Text = tmp;
                                        MainForm.textBox1.Text = MainForm.textBox1.Text + "寄存器\t读 OK！\r\n";
                                    }
                                    break;
                                case 0x03:
                                    {
                                        if (Rec_tmp[4] == 0x00) MainForm.textBox1.Text = MainForm.textBox1.Text + "OTP烧录\tOK！\r\n";
                                    }
                                    break;
                                case 0x23:
                                    {

                                        //private int[,] GVs = { { 0,1118,1183,1236,1282,1322,1359,1391,1421,1450,1498,1546,1581,1623,1682,1733, 1785,1826,1863,1899,1933,1971,1999,2024,2035,2042,3231},
                                        //{ 0,1118,1183,1236,1282,1322,1359,1391,1421,1450,1498,1546,1581,1623,1682,1733, 1785,1826,1863,1899,1933,1971,1999,2024,2035,2042,3233},
                                        //{ 0,1118,1183,1236,1282,1322,1359,1391,1421,1450,1498,1546,1581,1623,1682,1733, 1785,1826,1863,1899,1933,1971,1999,2024,2035,2042,3235} };

                                        for (int i = 0; i < 24; i++)
                                        {
                                            GVs[0, i] = ((Rec_tmp[2 * i + 4] & 0x0f) * 256 + Rec_tmp[2 * i + 5]);
                                            GVs[1, i] = ((Rec_tmp[2 * i + 4 + 48] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 48]);
                                            GVs[2, i] = ((Rec_tmp[2 * i + 4 + 96] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 96]);
                                        }

                                        txttip.Text = MainForm.textBox1.Text + "Gamma数据\t RGB全读 OK.\r\n";
                                    }
                                    break;
                                case 0x07:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            MainForm.textBox1.Text = MainForm.textBox1.Text + "OTP Successful !";
                                        else
                                            MainForm.textBox1.Text = MainForm.textBox1.Text + "手动检查是否烧录成功。";
                                    }
                                    break;
                                case 0x08://Write Gamma
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            MainForm.textBox1.Text = MainForm.textBox1.Text + "GAMMA \t写 OK！\r\n";
                                        else if (Rec_tmp[4] == 0x02)
                                            MainForm.textBox1.Text = MainForm.textBox1.Text + "GAMMA \t写 ERROR！\r\n";
                                    }
                                    break;
                                case 0x09://Read Gamma  Rec_tmp[4]未定义
                                    {

                                        if (Setting.TempRecord.ILI8818_GammaCmdType == 0x03)//Red Register
                                        {

                                            {

                                                for (int i = 0; i < 24; i++)
                                                {
                                                    GVs[0, i] = ((Rec_tmp[2 * i + 4] & 0x0f) * 256 + Rec_tmp[2 * i + 5]);
                                                    //GVs[1, i] = ((Rec_tmp[2 * i + 4 + 48] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 48]);
                                                    //GVs[2, i] = ((Rec_tmp[2 * i + 4 + 96] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 96]);
                                                }

                                                //num_ILI8818_R0.Value = Decimal.Parse((Rec_tmp[4] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[5].ToString());//0x03,最大0x03ff，0x0f,最大0x07ff
                                                //num_ILI8818_R1.Value = Decimal.Parse((Rec_tmp[6] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[7].ToString());
                                                //num_ILI8818_R2.Value = Decimal.Parse((Rec_tmp[8] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[9].ToString());
                                                //num_ILI8818_R3.Value = Decimal.Parse((Rec_tmp[10] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[11].ToString());
                                                //num_ILI8818_R4.Value = Decimal.Parse((Rec_tmp[12] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[13].ToString());
                                                //num_ILI8818_R5.Value = Decimal.Parse((Rec_tmp[14] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[15].ToString());
                                                //num_ILI8818_R6.Value = Decimal.Parse((Rec_tmp[16] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[17].ToString());
                                                //num_ILI8818_R7.Value = Decimal.Parse((Rec_tmp[18] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[19].ToString());
                                                //num_ILI8818_R8.Value = Decimal.Parse((Rec_tmp[20] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[21].ToString());
                                                //num_ILI8818_R9.Value = Decimal.Parse((Rec_tmp[22] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[23].ToString());
                                                //num_ILI8818_R10.Value = Decimal.Parse((Rec_tmp[24] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[25].ToString());
                                                //num_ILI8818_R11.Value = Decimal.Parse((Rec_tmp[26] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[27].ToString());

                                                //num_ILI8818_R12.Value = Decimal.Parse((Rec_tmp[28] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[29].ToString());
                                                //num_ILI8818_R13.Value = Decimal.Parse((Rec_tmp[30] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[31].ToString());
                                                //num_ILI8818_R14.Value = Decimal.Parse((Rec_tmp[32] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[33].ToString());
                                                //num_ILI8818_R15.Value = Decimal.Parse((Rec_tmp[34] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[35].ToString());
                                                //num_ILI8818_R16.Value = Decimal.Parse((Rec_tmp[36] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[37].ToString());
                                                //num_ILI8818_R17.Value = Decimal.Parse((Rec_tmp[38] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[39].ToString());
                                                //num_ILI8818_R18.Value = Decimal.Parse((Rec_tmp[40] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[41].ToString());
                                                //num_ILI8818_R19.Value = Decimal.Parse((Rec_tmp[42] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[43].ToString());
                                                //num_ILI8818_R20.Value = Decimal.Parse((Rec_tmp[44] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[45].ToString());
                                                //num_ILI8818_R21.Value = Decimal.Parse((Rec_tmp[46] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[47].ToString());
                                                //num_ILI8818_R22.Value = Decimal.Parse((Rec_tmp[48] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[49].ToString());
                                                //num_ILI8818_R23.Value = Decimal.Parse((Rec_tmp[50] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[51].ToString());

                                            }
                                            txttip.Text = MainForm.textBox1.Text + "Gamma数据\t R读 OK.\r\n";
                                            //MainForm.textBox1.Text = MainForm.textBox1.Text + "红 Gamma数据\t读 OK！\r\n";
                                        }
                                        else if (Setting.TempRecord.ILI8818_GammaCmdType == 0x04)//Green Register
                                        {

                                            {

                                                for (int i = 0; i < 24; i++)
                                                {
                                                    GVs[1, i] = ((Rec_tmp[2 * i + 4] & 0x0f) * 256 + Rec_tmp[2 * i + 5]);
                                                    //GVs[1, i] = ((Rec_tmp[2 * i + 4 + 48] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 48]);
                                                    //GVs[2, i] = ((Rec_tmp[2 * i + 4 + 96] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 96]);
                                                }
                                                //num_ILI8818_G0.Value = Decimal.Parse((Rec_tmp[4] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[5].ToString());
                                                //num_ILI8818_G1.Value = Decimal.Parse((Rec_tmp[6] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[7].ToString());
                                                //num_ILI8818_G2.Value = Decimal.Parse((Rec_tmp[8] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[9].ToString());
                                                //num_ILI8818_G3.Value = Decimal.Parse((Rec_tmp[10] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[11].ToString());
                                                //num_ILI8818_G4.Value = Decimal.Parse((Rec_tmp[12] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[13].ToString());
                                                //num_ILI8818_G5.Value = Decimal.Parse((Rec_tmp[14] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[15].ToString());
                                                //num_ILI8818_G6.Value = Decimal.Parse((Rec_tmp[16] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[17].ToString());
                                                //num_ILI8818_G7.Value = Decimal.Parse((Rec_tmp[18] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[19].ToString());
                                                //num_ILI8818_G8.Value = Decimal.Parse((Rec_tmp[20] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[21].ToString());
                                                //num_ILI8818_G9.Value = Decimal.Parse((Rec_tmp[22] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[23].ToString());
                                                //num_ILI8818_G10.Value = Decimal.Parse((Rec_tmp[24] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[25].ToString());
                                                //num_ILI8818_G11.Value = Decimal.Parse((Rec_tmp[26] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[27].ToString());

                                                //num_ILI8818_G12.Value = Decimal.Parse((Rec_tmp[28] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[29].ToString());
                                                //num_ILI8818_G13.Value = Decimal.Parse((Rec_tmp[30] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[31].ToString());
                                                //num_ILI8818_G14.Value = Decimal.Parse((Rec_tmp[32] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[33].ToString());
                                                //num_ILI8818_G15.Value = Decimal.Parse((Rec_tmp[34] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[35].ToString());
                                                //num_ILI8818_G16.Value = Decimal.Parse((Rec_tmp[36] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[37].ToString());
                                                //num_ILI8818_G17.Value = Decimal.Parse((Rec_tmp[38] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[39].ToString());
                                                //num_ILI8818_G18.Value = Decimal.Parse((Rec_tmp[40] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[41].ToString());
                                                //num_ILI8818_G19.Value = Decimal.Parse((Rec_tmp[42] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[43].ToString());
                                                //num_ILI8818_G20.Value = Decimal.Parse((Rec_tmp[44] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[45].ToString());
                                                //num_ILI8818_G21.Value = Decimal.Parse((Rec_tmp[46] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[47].ToString());
                                                //num_ILI8818_G22.Value = Decimal.Parse((Rec_tmp[48] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[49].ToString());
                                                //num_ILI8818_G23.Value = Decimal.Parse((Rec_tmp[50] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[51].ToString());

                                            }
                                            txttip.Text = MainForm.textBox1.Text + "Gamma数据\t G 读 OK.\r\n";
                                        }
                                        else if (Setting.TempRecord.ILI8818_GammaCmdType == 0x05)//Blue Register
                                        {

                                            {
                                                //num_ILI8818_B0.Value = Decimal.Parse((Rec_tmp[4] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[5].ToString());
                                                //num_ILI8818_B1.Value = Decimal.Parse((Rec_tmp[6] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[7].ToString());
                                                //num_ILI8818_B2.Value = Decimal.Parse((Rec_tmp[8] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[9].ToString());
                                                //num_ILI8818_B3.Value = Decimal.Parse((Rec_tmp[10] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[11].ToString());
                                                //num_ILI8818_B4.Value = Decimal.Parse((Rec_tmp[12] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[13].ToString());
                                                //num_ILI8818_B5.Value = Decimal.Parse((Rec_tmp[14] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[15].ToString());
                                                //num_ILI8818_B6.Value = Decimal.Parse((Rec_tmp[16] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[17].ToString());
                                                //num_ILI8818_B7.Value = Decimal.Parse((Rec_tmp[18] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[19].ToString());
                                                //num_ILI8818_B8.Value = Decimal.Parse((Rec_tmp[20] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[21].ToString());
                                                //num_ILI8818_B9.Value = Decimal.Parse((Rec_tmp[22] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[23].ToString());
                                                //num_ILI8818_B10.Value = Decimal.Parse((Rec_tmp[24] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[25].ToString());
                                                //num_ILI8818_B11.Value = Decimal.Parse((Rec_tmp[26] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[27].ToString());

                                                //num_ILI8818_B12.Value = Decimal.Parse((Rec_tmp[28] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[29].ToString());
                                                //num_ILI8818_B13.Value = Decimal.Parse((Rec_tmp[30] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[31].ToString());
                                                //num_ILI8818_B14.Value = Decimal.Parse((Rec_tmp[32] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[33].ToString());
                                                //num_ILI8818_B15.Value = Decimal.Parse((Rec_tmp[34] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[35].ToString());
                                                //num_ILI8818_B16.Value = Decimal.Parse((Rec_tmp[36] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[37].ToString());
                                                //num_ILI8818_B17.Value = Decimal.Parse((Rec_tmp[38] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[39].ToString());
                                                //num_ILI8818_B18.Value = Decimal.Parse((Rec_tmp[40] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[41].ToString());
                                                //num_ILI8818_B19.Value = Decimal.Parse((Rec_tmp[42] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[43].ToString());
                                                //num_ILI8818_B20.Value = Decimal.Parse((Rec_tmp[44] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[45].ToString());
                                                //num_ILI8818_B21.Value = Decimal.Parse((Rec_tmp[46] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[47].ToString());
                                                //num_ILI8818_B22.Value = Decimal.Parse((Rec_tmp[48] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[49].ToString());
                                                //num_ILI8818_B23.Value = Decimal.Parse((Rec_tmp[50] & 0x0f).ToString()) * 256 + Decimal.Parse(Rec_tmp[51].ToString());
                                                for (int i = 0; i < 24; i++)
                                                {
                                                    GVs[2, i] = ((Rec_tmp[2 * i + 4] & 0x0f) * 256 + Rec_tmp[2 * i + 5]);
                                                    //GVs[1, i] = ((Rec_tmp[2 * i + 4 + 48] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 48]);
                                                    //GVs[2, i] = ((Rec_tmp[2 * i + 4 + 96] & 0x0f) * 256 + Rec_tmp[2 * i + 5 + 96]);
                                                }
                                                txttip.Text = MainForm.textBox1.Text + "Gamma数据\t B读 OK.\r\n";
                                            }
                                            //txttip.Text = MainForm.textBox1.Text + "Gamma数据\t RGB全读 OK.\r\n";
                                        }
                                    }
                                    break;
                                default: break;
                            }
                        }
                        //--------------------------------------------通用读写----------------------------------------------
                        else if (Rec_tmp[0] == 0x99) //GENWR
                        {
                            switch (Rec_tmp[1])
                            {
                                case 0x01:
                                    {
                                        if (Rec_tmp[4] == 0x00)
                                            txttip.Text = txttip.Text + "DDIC 寄存器\t写 OK！\r\n";
                                    }
                                    break;
                                case 0x02:
                                    {
                                        string tmp = "";                    //8bit  read
                                        {
                                            for (int i = 3; i <= (Rec_tmp[2] + 2); i++)
                                            {
                                                if (i == (Rec_tmp[2] + 2))
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]);//16进制
                                                }
                                                else
                                                {
                                                    tmp = tmp + String.Format("{0:X2}", Rec_tmp[i]) + ",";//16进制
                                                }
                                                // ReadBackarr[i] = Rec_tmp[i];
                                            }
                                            //    //---------------------Gamma  R --------------------
                                            //    if ((Rec_tmp[3] == 0xb0) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[(i - 4) >> 1, 0] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    else if ((Rec_tmp[3] == 0xb1) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[((i - 4) >> 1) + 8, 0] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    else if ((Rec_tmp[3] == 0xb2) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[((i - 4) >> 1) + 16, 0] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    else if ((Rec_tmp[3] == 0xb3) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[((i - 4) >> 1) + 24, 0] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    //---------------------Gamma  G --------------------
                                            //    else if ((Rec_tmp[3] == 0xb4) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[(i - 4) >> 1, 1] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    else if ((Rec_tmp[3] == 0xb5) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[((i - 4) >> 1) + 8, 1] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    else if ((Rec_tmp[3] == 0xb6) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[((i - 4) >> 1) + 16, 1] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    else if ((Rec_tmp[3] == 0xb7) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[((i - 4) >> 1) + 24, 1] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    //---------------------Gamma  B --------------------
                                            //    else if ((Rec_tmp[3] == 0xb8) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[(i - 4) >> 1, 2] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    else if ((Rec_tmp[3] == 0xb9) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[((i - 4) >> 1) + 8, 2] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    else if ((Rec_tmp[3] == 0xbA) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[((i - 4) >> 1) + 16, 2] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    else if ((Rec_tmp[3] == 0xbB) && GammaReadBackFlag)
                                            //    {
                                            //        for (int i = 4; i <= (Rec_tmp[2] + 2); i += 2)
                                            //        {
                                            //            GammaValue[((i - 4) >> 1) + 24, 2] = (uint)((Rec_tmp[i] << 8) + Rec_tmp[i + 1]);
                                            //        }
                                            //    }
                                            //    GammaReadBackFlag = false;
                                        }
                                        txttip.Text += "DDIC 8bit寄存器--读 OK！\r\n";
                                        txttip.AppendText(tmp + "\r\n");

                                        Application.DoEvents();
                                    }
                                    break;
                                case 0x03:
                                    {
                                        string tmp = "";
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[3]) + ",";  //16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[4]) + ",";//16进制
                                        tmp = tmp + String.Format("{0:X2}", Rec_tmp[5]);      //16进制

                                        txttip.Text += "DDIC 16bit寄存器--读 OK！\r\n";
                                        txttip.AppendText(tmp + "\r\n");

                                        Application.DoEvents();

                                    }
                                    break;
                                case 0x04:
                                    {
                                        if (Rec_tmp[3] == 0x00)
                                        {
                                            txttip.Text += "vpp off！\r\n";
                                        }
                                        else if (Rec_tmp[3] == 0x01)
                                        {
                                            txttip.Text += "vpp on！\r\n";
                                        }
                                    }
                                    break;
                            }
                        }
                        //----------------------------------------------------------------------------------------------------                       
                        else if (Rec_tmp[0] == 0x9f)    //小黄窗的通用命令读写
                        {
                            txttip.Text += "[" + DateTime.Now.ToLongTimeString().ToString() + "]：" + "命令已执行" + "\r\n";
                            txttip.SelectionStart = this.txttip.Text.Length;
                            txttip.ScrollToCaret();//滚动到光标处
                            if (txttip.Lines.Length > 500) txttip.Text = null;
                        }
                        ////---------------------------------------------------Demura----------------------------------------
                        else if (Rec_tmp[0] == 0x2F)  //Demura
                        {
                            if ((Rec_tmp[7] == 0x2E) || (Rec_tmp[7] == 0x3C))   // 297/298/299  //350
                            {
                                if (Rec_tmp[7] == 0x2E)// 297/298/299
                                {
                                    txttip.Text = txttip.Text + "297 298 299\r\n";
                                }
                                else if (Rec_tmp[7] == 0x3C) //350
                                {
                                    txttip.Text = txttip.Text + "350\r\n";
                                }
                                switch (Rec_tmp[1])
                                {
                                    case 0x01:
                                        {
                                            txttip.Text = txttip.Text + "Demura RAM Enable\r\n";
                                        }
                                        break;
                                    case 0x02:
                                        {
                                            txttip.Text = txttip.Text + "Demura RAM Disable\r\n";
                                        }
                                        break;
                                    case 0x03:
                                        {
                                            if (Rec_tmp[7] == 0x2E)// 297/298/299
                                            {
                                                if (Rec_tmp[4] == 0x80)
                                                {
                                                    txttip.Text = txttip.Text + "Demura RAM write Flash complete ! \r\n";
                                                }
                                            }
                                            else if (Rec_tmp[7] == 0x3C) ///350
                                            {
                                                if (Rec_tmp[4] == 0x08)
                                                {
                                                    txttip.Text = txttip.Text + "Demura RAM write Flash1 complete ! \r\n";
                                                }
                                            }
                                        }
                                        break;
                                    case 0x0A:///350 only
                                        {
                                            if (Rec_tmp[7] == 0x3C) ///350
                                            {
                                                if (Rec_tmp[4] == 0x08)
                                                {
                                                    txttip.Text = txttip.Text + "Demura RAM write Flash2 complete ! \r\n";
                                                }
                                            }
                                        }
                                        break;
                                    case 0x04:
                                        {
                                            txttip.Text = txttip.Text + "Checksum: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "\r\n";
                                        }
                                        break;
                                    case 0x05:
                                        {
                                            if (Rec_tmp[7] == 0x2E)// 297/298/299
                                            {
                                                if (Rec_tmp[4] == 0x80)
                                                {
                                                    txttip.Text = txttip.Text + "Flash Erase Success ! \r\n";
                                                }
                                            }
                                            else if (Rec_tmp[7] == 0x3C) ///350
                                            {
                                                if (Rec_tmp[4] == 0x08)
                                                {
                                                    txttip.Text = txttip.Text + "Flash Erase Success ! \r\n";
                                                }
                                            }
                                        }
                                        break;
                                    case 0x06:
                                        {
                                            txttip.Text = txttip.Text + "flash ID: " + Rec_tmp[4].ToString("x") + "," + Rec_tmp[5].ToString("x") + "," + Rec_tmp[6].ToString("x") + "\r\n";
                                        }
                                        break;
                                    case 0x07:
                                        {
                                            txttip.Text = txttip.Text + "Demura function on \r\n";
                                        }
                                        break;
                                    case 0x08:
                                        {
                                            txttip.Text = txttip.Text + "Demura function off \r\n";
                                        }
                                        break;
                                    case 0x09:
                                        {
                                            txttip.Text = txttip.Text + "Demura OTP complete$ \r\n";
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                        txttip.Focus();//获取焦点
                        txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
                        txttip.ScrollToCaret();//滚动到光标处
                        if (txttip.Lines.Length > 200) txttip.Text = "";

                    }));
                }
            }
            finally
            {
                Listening = false;

            }
        }
        //=================================LCD cfg function:OLED_Show_Click====Start=================
        private void OLED_Show_Click(object sender, EventArgs e)
        {
            if (!chkBISTMode.Checked)
            {
                Send_buf = new byte[25];
                Button btnTmp = (Button)sender;
                Setting.TempRecord.cmdLen = 25;
                Send_buf[0] = 0x0A; //LCD配置标志
                Send_buf[2] = 0x15; //数据长度
                switch (btnTmp.Name)
                {
                    case "btnPatternW":                             //写入Pattern参数
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = byte.Parse(numPatternR.Value.ToString());
                            Send_buf[4] = byte.Parse(numPatternG.Value.ToString());
                            Send_buf[5] = byte.Parse(numPatternB.Value.ToString());
                        }
                        break;
                    case "btnred":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0;
                        }
                        break; //R
                    case "btngreen":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0;
                        }
                        break; //G
                    case "btnblue":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0xFF;
                        }
                        break; //B
                    case "btnwhite":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0xFF;
                        }
                        break; //W
                    case "btnblack":
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0;
                            Send_buf[4] = 0;
                            Send_buf[5] = 0;
                        }
                        break; //BL
                    default:
                        {
                            Send_buf[1] = 0x07;
                            Send_buf[3] = 0xFF;
                            Send_buf[4] = 0xFF;
                            Send_buf[5] = 0xFF;
                        }
                        break;
                }

                CRCData.CalculateCrc16(Send_buf, out Send_buf[23], out Send_buf[24]);
                try
                {
                    MainForm.comPort.Write(Send_buf, 0, 25);
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                }
                Thread.Sleep(8);
            }
            else
            {
                Button btnTmp = (Button)sender;
                byte[] TepArr;
                byte FRM_PT = 1; //white

                switch (btnTmp.Name)
                {
                    case "btnred":
                        {
                            FRM_PT = 4;  //red
                            txttip.Text += "---R---" + "\r\n";
                        }
                        break;
                    case "btngreen":
                        {
                            FRM_PT = 8;  //green
                            txttip.Text += "---G---" + "\r\n";
                            break;
                        }
                    case "btnblue":
                        {
                            FRM_PT = 0x10;
                            txttip.Text += "---B---" + "\r\n";
                            break;
                        }
                    case "btnwhite":
                        {
                            FRM_PT = 1;  //
                            txttip.Text += "---WHITE---" + "\r\n";
                        }
                        break;
                    case "btnblack":
                        {
                            FRM_PT = 2;  //
                            txttip.Text += "---BLACK---" + "\r\n";
                        }
                        break;

                    default: break;
                }

                TepArr = new byte[] {
                        4,0xff,0x78,0x38,0x02,
                        //2,0xa2,0x00,
                        2,0x1b,0x04,  //data shift 关闭， 120Hz时导致ip工作时间不够，显示异常，故120Hz初始化时开启了datashift功能
                        2,0x88, FRM_PT,
                        2,0x89,0x00,
                        2,0x8a,0x00,

                        2,0x8c, 00 ,    //// SET FRAME DURATION 64 FRAME ~ 1S                       
                        2,0xa5,0x01,  // // BIST MODE ENABLE
                       };
                try
                {
                    MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }
            if (chkLvTest.Checked)
            {
                Msr_CA310();
                txttip.Text = "当前亮度：" + auto_lum + "\r\n";
            }
        }

        private void numPatternR_ValueChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternR.Value;
            }
            btnBISTGrayShow.PerformClick();
            //Thread.Sleep(2);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                numPatternG.Value = numPatternR.Value;
                numPatternB.Value = numPatternG.Value;
                numPatternG.Enabled = false;
                numPatternB.Enabled = false;
            }
            else
            {
                numPatternG.Enabled = true;
                numPatternB.Enabled = true;
            }
        }
        private void GR_WriteRead_Click(object sender, EventArgs e)          //上位机使用通用命令读写方式操作DDIC
        {
            string str = txtRegSend.Text.ToString();
            byte DDICReg; byte readnum;
            string[] arr;
            arr = str.Split(',');
            Setting.TempRecord.cmdLen = arr.Length + 5;
            //Send_buf = new byte[Setting.TempRecord.cmdLen];
            //Send_buf[2] = Convert.ToByte(arr.Length);
            Button btnTmp = (Button)sender;
            //Send_buf[0] = 0x6B;

            switch (btnTmp.Name)
            {
                case "writeReg":
                    {
                        String text;
                        text = txtRegSend.Text;
                        MainForm.txtProcessDrivercode(text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
                        {
                            MainForm.SendCmd(0);  //低速
                        }
                        else
                        {
                            MainForm.SendCmd(4); //高速
                        }
                        txttip.Text += "命令已下发...\r\n";
                        txttip.Select(txttip.Text.Length, 0);
                        txttip.ScrollToCaret();
                    }
                    break;
                case "readReg":
                    {
                        //VTDR6100_0XFE_XX = 0x00;
                        //Send_buf[1] = 0x02;
                        DDICReg = byte.Parse(Convert.ToUInt32(arr[0], 16).ToString());
                        readnum = byte.Parse(Convert.ToUInt32(arr[1], 16).ToString());
                        MainForm.GeneralRegRead(DDICReg, readnum);
                    }
                    break;

                default:
                    break;
            }
            //for (int i = 0; i < arr.Length; i++)
            //{
            //    Send_buf[3 + i] = byte.Parse(Convert.ToUInt32(arr[i], 16).ToString());
            //}
            //CRCData.CalculateCrc16(Send_buf, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
            //try
            //{
            //    frmTop.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);
            //}
            //catch
            //{
            //    MessageBox.Show("串口有误，请检查", "错误");
            //}
            MainForm.T1.Enabled = false;
            MainForm.T1.Interval = 2000;
            MainForm.T1.Enabled = true;
        }           //上位机使用通用命令读写方式操作DDIC
        //------------------------------------------Demura------------------------------------------------        
        private void Msr_CA310()
        {
            MainForm.Msr_CASDK();
            auto_lum = MainForm.CASDK_LUM;
            auto_x = MainForm.CASDK_x;
            auto_y = MainForm.CASDK_y;
        }
        //=================================LCD cfg function: OLED_Show_Click====end=================

        private int adjust_num = 0;
        private string adjust_class = null;
        private double[,] D_lums;//目标值-单色
        private double[] D_lum;//目标值-白色
        private double D_x, D_y;

        private int index = 0;

        private double lum_off, x_off, y_off;
        private double R_x = 0.67;//
        private double R_y = 0.33;
        private double G_x = 0.22;
        private double G_y = 0.71;
        private double B_x = 0.14;
        private double B_y = 0.06;
        private void btnBack_Click(object sender, EventArgs e)
        {
            MainForm.comPort.DataReceived -= new SerialDataReceivedEventHandler(SerialPort1_DataReceived);//移除本窗口串口处理函数
            MainForm.comPort.DataReceived += new SerialDataReceivedEventHandler(MainForm.SerialPort1_DataReceived);//
            MainForm.Show();
            this.Hide();
        }
        private void ILI7838_644_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }
        private void ILI7838_644_FormClosed(object sender, FormClosedEventArgs e)
        {
            ////MainForm.comPort.Close()
            MainForm.comPort.DataReceived -= new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
            MainForm.comPort.DataReceived += new SerialDataReceivedEventHandler(MainForm.SerialPort1_DataReceived);
            ////MainForm.comPort.Open();
            MainForm.textBox1.Text = MainForm.textBox1.Text + "7838/8818_FormClosed！\r\n";
            MainForm.Child_Gamma_Window_Open_Enable = true; //允许其他子窗体打开
            MainForm.Child_window_hide_already = false;
            MainForm.IC_comboBox.Enabled = true;
            firstGammaFlag = true;
        }
        private void ILI7838_644_VisibleChanged(object sender, EventArgs e)
        {

            if (MainForm.Child_window_hide_already == false) //子窗体已开启标识
            {
                ////MainForm.comPort.Close()
                MainForm.comPort.DataReceived -= new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
                MainForm.comPort.DataReceived += new SerialDataReceivedEventHandler(MainForm.SerialPort1_DataReceived);
                ////MainForm.comPort.Open();
                MainForm.textBox1.Text = MainForm.textBox1.Text + "ILI78388818_Gamma_FormHide！\r\n";
                MainForm.Child_window_hide_already = true; //子窗体已隐藏标识
            }
            else
            {
                MainForm.comPort.DataReceived -= new SerialDataReceivedEventHandler(MainForm.SerialPort1_DataReceived);
                MainForm.comPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
                MainForm.textBox1.Text = MainForm.textBox1.Text + "ILI78388818_Gamma_FormOpened！\r\n";
                MainForm.Child_window_hide_already = false; //子窗体已开启标识
            }

        }
        void Page0Set()
        {
            byte[] TepArr;
            TepArr = new byte[] {                
                //切Page 
                4,0xff,0x78,0x38,0x00,
                       };
            try
            {
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }

        }
        #region //------Gamma 调整模块---------------
        byte[,] GP;
        //Gamma RGB 默认初始值
        private int[,] GVs = { { 0,1118,1183,1236,1282,1322,1359,1391,1421,1450,1498,1546,1581,1623,1682,1733, 1785,1826,1863,1899,1933,1971,1999,2024,2035,2042,3631},
                                        { 0,1118,1183,1236,1282,1322,1359,1391,1421,1450,1498,1546,1581,1623,1682,1733, 1785,1826,1863,1899,1933,1971,1999,2024,2035,2042,3733},
                                        { 0,1118,1183,1236,1282,1322,1359,1391,1421,1450,1498,1546,1581,1623,1682,1733, 1785,1826,1863,1899,1933,1971,1999,2024,2035,2042,3835} };
        private void CheckandCorrectGammaValue() //检查Gamma帮点寄存器的值是否存在高低灰阶反转，若有则强制修正；
        {
            byte i, j;
            for (j = 0; j < 3; j++)
            {
                for (i = 0; i < PointNum - 1; i++)  //从第2个数开始检查至
                {
                    if (GVs[j, PointNum - 1 - i - 1] > GVs[j, PointNum - 1 - i])
                    {
                        GVs[j, PointNum - 1 - i - 1] = (GVs[j, PointNum - 1 - i] - 1);
                    }
                    if (GVs[j, PointNum - 1 - i - 1] < 1)
                    {
                        GVs[j, PointNum - 1 - i - 1] = 1;
                    }
                }
            }
        }

        byte Gpage = 0x20;
        byte GFrame = 0; //Gamma 对应的帧频
        void GammaValueSet()
        {
            byte GammaPage = 0x20;
            byte[] TepArr;
            if (chkGammaPageManualSet.Checked)   //判断是否手动设定GammaPage
            {
                GammaPage = (byte)(numGammaPage.Value);
            }
            else { GammaPage = Gpage; } //判断是否手动设定GammaPage

            if (chkAODGamma.Checked)
            {
                TepArr = new byte[] { 
                // Normal mode  
                //切Page 0
                4,0xff,0x78,0x38,0x00,
                1,39,
                4,0xff,0xff,0xff,0x1f,
                 4,0xff,0x78,0x38,0x0c,
                4,0xff,0xff,0xff,0x1f,
                2,0xe3,0x01,     //解锁Gamma
                4,0xff,0x78,0x38,0x35,   //切回NormalGamma 所在Page
                4,0xff,0xff,0xff,0x1f,
                    //-------------------------Gamma R ,G, B------
                    //R0~R7寄存器
                    0x7,0x00,GP[0,  0],GP[0, 01],GP[1,   0],GP[1, 01],GP[2,  0],GP[2, 01],
                    0x7,0x02,GP[0,  2],GP[0, 03],GP[1,   2],GP[1, 03],GP[2,  2],GP[2, 03],
                    0x7,0x03,GP[0,  4],GP[0, 05],GP[1,   4],GP[1, 05],GP[2,  4],GP[2, 05],
                    0x7,0x04,GP[0,  6],GP[0, 07],GP[1,   6],GP[1, 07],GP[2,  6],GP[2, 07],
                    0x7,0x05,GP[0,  8],GP[0, 09],GP[1,   8],GP[1, 09],GP[2,  8],GP[2, 09],
                    0x7,0x06,GP[0, 10],GP[0, 11],GP[1, 10],GP[1, 11],GP[2,10],GP[2,  11],
                    0x7,0x07,GP[0, 12],GP[0, 13],GP[1, 12],GP[1, 13],GP[2,12],GP[2,  13],
                    0x7,0x08,GP[0, 14],GP[0, 15],GP[1, 14],GP[1, 15],GP[2,14],GP[2,  15],
                    0x7,0x09,GP[0, 16],GP[0, 17],GP[1, 16],GP[1, 17],GP[2,16],GP[2,  17],
                    0x7,0x0a,GP[0, 18],GP[0, 19],GP[1, 18],GP[1, 19],GP[2,18],GP[2,  19],
                    0x7,0x0b,GP[0, 20],GP[0, 21],GP[1, 20],GP[1, 21],GP[2,20 ],GP[2, 21 ],
                    0x7,0x0c,GP[0, 22],GP[0, 23],GP[1, 22],GP[1,  23],GP[2,22 ],GP[2, 23 ],
                    0x7,0x0d,GP[0, 24],GP[0, 25],GP[1, 24],GP[1, 25],GP[2,24 ],GP[2 ,25 ],
                    0x7,14   ,GP[0, 26],GP[0, 27],GP[1, 26],GP[1, 27],GP [2,26 ],GP[2,27 ],
                    0x7,0x0f,GP[0, 28],GP [0, 29],GP[1, 28],GP[1, 29],GP[2,28 ],GP[2, 29 ],
                    0x7,0x10,GP[0, 30],GP[0, 31],GP[1, 30],GP[1, 31],GP[2,30],GP[2,  31],
                    0x7,17   ,GP[0, 32],GP[0, 33],GP[1,  32],GP[1,33 ],GP[2,32],GP[2,33 ],
                    0x7,18   ,GP[0, 34],GP[0, 35],GP[1,  34],GP[1,35 ],GP[2,34],GP[2,35 ],
                    0x7,19   ,GP[0, 36],GP[0, 37],GP[1,  36],GP[1,37 ],GP[2,36],GP[2,37 ],
                    0x7,20   ,GP[0, 38],GP[0, 39],GP[1,  38],GP[1,39 ],GP[2,38],GP[2,39 ],
                    0x7,21   ,GP[0, 40],GP[0, 41],GP[1,  40],GP[1,41 ],GP[2,40],GP[2,41 ],
                    0x7,22   ,GP[0, 42],GP[0, 43],GP[1,  42],GP[1,43 ],GP[2,42],GP[2,43 ],
                    0x7,23   ,GP[0, 44],GP[0, 45],GP[1,  44],GP[1,45 ],GP[2,44],GP[2,45 ],
                    0x7,24   ,GP[0, 46],GP[0, 47],GP[1,  46],GP[1,47 ],GP[2,46],GP[2,47 ],
                    4,0xff,0x78,0x38,0x0c,  //切page
                    2,0xe3,0x00,     //Lock Gamma
                    4,0xff,0xff,0xff,0x1f,
                    4,0xff,0x78,0x38,00,  //切回Page 0 以便于画面显示
                       };

            }
            else
            {
                TepArr = new byte[] { 
                // Normal mode  
                4,0xff,0x78,0x38,0x2,
                4,0xff,0xff,0xff,0x1f,
                2,0x38,GFrame,
                4,0xff,0x78,0x38,0x0c,
                4,0xff,0xff,0xff,0x1f,
                2,0xe3,0x01,     //解锁Gamma
                4,0xff,0x78,0x38,GammaPage,   //切回NormalGamma 所在Page
                4,0xff,0xff,0xff,0x1f,
                    //-------------------------Gamma R ,G, B------
                    //R0~R7寄存器
                    0x7,0x00,GP[0,  0],GP[0, 01],GP[1,   0],GP[1, 01],GP[2,  0],GP[2, 01],
                    0x7,0x02,GP[0,  2],GP[0, 03],GP[1,   2],GP[1, 03],GP[2,  2],GP[2, 03],
                    0x7,0x03,GP[0,  4],GP[0, 05],GP[1,   4],GP[1, 05],GP[2,  4],GP[2, 05],
                    0x7,0x04,GP[0,  6],GP[0, 07],GP[1,   6],GP[1, 07],GP[2,  6],GP[2, 07],
                    0x7,0x05,GP[0,  8],GP[0, 09],GP[1,   8],GP[1, 09],GP[2,  8],GP[2, 09],
                    0x7,0x06,GP[0, 10],GP[0, 11],GP[1, 10],GP[1, 11],GP[2,10],GP[2,  11],
                    0x7,0x07,GP[0, 12],GP[0, 13],GP[1, 12],GP[1, 13],GP[2,12],GP[2,  13],
                    0x7,0x08,GP[0, 14],GP[0, 15],GP[1, 14],GP[1, 15],GP[2,14],GP[2,  15],
                    0x7,0x09,GP[0, 16],GP[0, 17],GP[1, 16],GP[1, 17],GP[2,16],GP[2,  17],
                    0x7,0x0a,GP[0, 18],GP[0, 19],GP[1, 18],GP[1, 19],GP[2,18],GP[2,  19],
                    0x7,0x0b,GP[0, 20],GP[0, 21],GP[1, 20],GP[1, 21],GP[2,20 ],GP[2, 21 ],
                    0x7,0x0c,GP[0, 22],GP[0, 23],GP[1, 22],GP[1,  23],GP[2,22 ],GP[2, 23 ],
                    0x7,0x0d,GP[0, 24],GP[0, 25],GP[1, 24],GP[1, 25],GP[2,24 ],GP[2 ,25 ],
                    0x7,14   ,GP[0, 26],GP[0, 27],GP[1, 26],GP[1, 27],GP [2,26 ],GP[2,27 ],
                    0x7,0x0f,GP[0, 28],GP [0, 29],GP[1, 28],GP[1, 29],GP[2,28 ],GP[2, 29 ],
                    0x7,0x10,GP[0, 30],GP[0, 31],GP[1, 30],GP[1, 31],GP[2,30],GP[2,  31],
                    0x7,17   ,GP[0, 32],GP[0, 33],GP[1,  32],GP[1,33 ],GP[2,32],GP[2,33 ],
                    0x7,18   ,GP[0, 34],GP[0, 35],GP[1,  34],GP[1,35 ],GP[2,34],GP[2,35 ],
                    0x7,19   ,GP[0, 36],GP[0, 37],GP[1,  36],GP[1,37 ],GP[2,36],GP[2,37 ],
                    0x7,20   ,GP[0, 38],GP[0, 39],GP[1,  38],GP[1,39 ],GP[2,38],GP[2,39 ],
                    0x7,21   ,GP[0, 40],GP[0, 41],GP[1,  40],GP[1,41 ],GP[2,40],GP[2,41 ],
                    0x7,22   ,GP[0, 42],GP[0, 43],GP[1,  42],GP[1,43 ],GP[2,42],GP[2,43 ],
                    0x7,23   ,GP[0, 44],GP[0, 45],GP[1,  44],GP[1,45 ],GP[2,44],GP[2,45 ],
                    0x7,24   ,GP[0, 46],GP[0, 47],GP[1,  46],GP[1,47 ],GP[2,46],GP[2,47 ],
                    4,0xff,0x78,0x38,0x0c,  //切page
                    2,0xe3,0x00,     //Lock Gamma
                    4,0xff,0xff,0xff,0x1f,
                    4,0xff,0x78,0x38,00,  //切回Page 0 以便于画面显示
                       };
            }

            try
            {
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }
        void GValue_Format_set()  //把Gamma RGB的寄存器值转换为便于写入DDIC 的格式
        {
            int i, j;
            GP = new byte[3, 54];

            for (j = 0; j < 3; j++)
            {
                for (i = 0; i < 24; i++)
                {
                    GP[j, 2 * i] = (byte)((GVs[j, i] & 0xff00) >> 8);
                    GP[j, 2 * i + 1] = (byte)(GVs[j, i] & 0xff);
                }
            }
            if (chkGammaGridViewFresh.Checked)   // 刷新UI界面GammaValue值显示
            {
                for (i = 0; i < 24; i++)//有一行标题
                {
                    GammaReg_dataGridView.Rows[i].Cells[2].Value = GVs[0, i];
                    GammaReg_dataGridView.Rows[i].Cells[3].Value = GVs[1, i];
                    GammaReg_dataGridView.Rows[i].Cells[4].Value = GVs[2, i];
                    //------------------------------------
                }
            }
        }
        byte rstep = 16; byte gstep = 16; byte bstep = 16;
        #region  //Gamma调整计时
        System.DateTime TimeNow = new DateTime();
        TimeSpan TimeCount = new TimeSpan();
        private void TimTest_Tick(object sender, EventArgs e)
        {
            TimeCount = DateTime.Now - TimeNow;
            txtTimeShow.Text = string.Format("{0:00}:{1:00}:{2:00}", TimeCount.Hours, TimeCount.Minutes, TimeCount.Seconds);
        }
        #endregion
        private int[] Point_ILI7838_644 = new int[24] {//---Gamma绑点数据，这里的数据仅供参考---
           0,1,2,4,6,9,12,16,20,24,30,36,42,50,57,65,77,94,112,135,170,206,220,255};
        int PointNum = 24; // Point_ILI7838_644.Length;
        private void btnAutoGammas_ILI7838_644_Click(object sender, EventArgs e)
        {
            int flag = 1;
            STOPGammaFlag = false;
            double Lr_d, Lg_d, Lb_d;
            D_lums = new double[27, 3];
            D_lum = new double[27];
            index = 1;
            //if (chkGammamodeAutoSet.Checked)
            //{ GammaModeSet(); }

            flag3 = flag1 = flag2 = 1;
            rstep = (byte)(int.Parse(numStep.Value.ToString()));
            gstep = (byte)(int.Parse(numStep.Value.ToString()));
            bstep = (byte)(int.Parse(numStep.Value.ToString()));

            TimTest.Start();
            TimeNow = DateTime.Now; //开始计时

            for (int i = 0; i < 24; i++)
            {
                D_lum[i] = (Math.Pow((Point_ILI7838_644[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
            }

            D_x = Convert.ToDouble(txtVT_x.Text);
            D_y = Convert.ToDouble(txtVT_y.Text);
            Lr_d = R_y * ((D_y - G_y) * (B_x - D_x) + (D_x - G_x) * (D_y - B_y)) / B_y / ((D_y - G_y) * (D_x - R_x) + (D_x - G_x) * (R_y - D_y));
            Lb_d = 1.0;
            Lg_d = G_y * ((D_y - R_y) * (B_x - D_x) + (D_x - R_x) * (D_y - B_y)) / B_y / ((D_y - R_y) * (D_x - G_x) + (D_x - R_x) * (G_y - D_y));

            for (int i = 0; i < 24; i++)
            {
                D_lums[i, 0] = D_lum[i] * Lr_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 1] = D_lum[i] * Lg_d / (Lr_d + Lg_d + Lb_d);
                D_lums[i, 2] = D_lum[i] * Lb_d / (Lr_d + Lg_d + Lb_d);
            }

            switch (flag)
            {
                case 1://寄存器值与亮度正比
                    {
                        //lum_off = Convert.ToDouble(txtVT_loff.Text);
                        x_off = Convert.ToDouble(txtVT_xoff.Text);
                        y_off = Convert.ToDouble(txtVT_yoff.Text);
                        if (chkBISTMode.Checked)
                        {
                            numPatternR.Value = 255;
                            btnBISTGrayShow.PerformClick();
                        }
                        else
                        {
                            Page0Set();
                            OLED_Show_Click(btnwhite, e);
                            Thread.Sleep(10);
                            Msr_CA310();
                        }
                        //ReceivOKFlag = false;
                        T17.Enabled = true;
                    }
                    break;
                case 2:  //寄存器值与亮度反比
                    break;
                default:
                    break;
            }
        }
        bool lastdirupR = true; bool lastdirupG = true; bool lastdirupB = true; // Gamma 调整方向
        UInt32 timeout = 0;
        private void T17_Tick(object sender, EventArgs e)
        {
            double Lr_t, Lg_t, Lb_t, lumr, lumg, lumb;
            T17.Enabled = false;
            T17.Interval = 20;
            Msr_CA310();

            txtlvshow.Text = "Lv: " + auto_lum + "\r\n" + "x: " + auto_x.ToString("#0.0000") + "\r\n" + "y: " + auto_y.ToString("#0.0000") + "\r\n";
            // if (index > 2)
            labTargetlum.Text = "Tar:" + D_lum[24 - index].ToString("#0.00000");
            txttip.Text += "Adjust inex:" + "--------" + index + "\r\n";

            Lr_t = R_y * ((auto_y - G_y) * (B_x - auto_x) + (auto_x - G_x) * (auto_y - B_y)) / B_y / ((auto_y - G_y) * (auto_x - R_x) + (auto_x - G_x) * (R_y - auto_y));
            Lb_t = 1.0;
            Lg_t = G_y * ((auto_y - R_y) * (B_x - auto_x) + (auto_x - R_x) * (auto_y - B_y)) / B_y / ((auto_y - R_y) * (auto_x - G_x) + (auto_x - R_x) * (G_y - auto_y));
            lumr = auto_lum * Lr_t / (Lr_t + Lg_t + Lb_t);
            lumg = auto_lum * Lg_t / (Lr_t + Lg_t + Lb_t);
            lumb = auto_lum * Lb_t / (Lr_t + Lg_t + Lb_t);

            lum_off = (D_lum[PointNum - index] * Convert.ToDouble(numVT_loff.Value) / 1000);
            x_off = Convert.ToDouble(txtVT_xoff.Text);
            y_off = Convert.ToDouble(txtVT_yoff.Text);

            if ((auto_lum < (D_lum[PointNum - index] + lum_off)) && (auto_lum > (D_lum[PointNum - index] - lum_off)))//
                flag1 = 0;
            if ((auto_y < (D_y + y_off)) && (auto_y > (D_y - y_off)) && flag1 == 0)//
                flag2 = 0;
            if ((auto_x < (D_x + x_off)) && (auto_x > (D_x - x_off)) && flag1 == 0)//
                flag3 = 0;

            if ((flag1 == 0 && flag2 == 0 && flag3 == 0) || (timeout > 3 * numTurnGammaTimeout.Value))
            {
                T17.Enabled = false;
                if (timeout > 3 * numTurnGammaTimeout.Value) { txttip.Text = "--模糊处理--\r\n" + "----模糊处理----\r\n" + "--------模糊处理--------\r\n" + "----模糊处理----\r\n" + "--模糊处理--\r\n"; }
                timeout = 0;
                index++;
                rstep = (byte)(int.Parse(numStep.Value.ToString()));
                gstep = (byte)(int.Parse(numStep.Value.ToString()));
                bstep = (byte)(int.Parse(numStep.Value.ToString()));
                if (index == PointNum)
                {
                    TimTest.Stop();//停止计时
                    txttip.Text = txttip.Text + "ILI7838_644 Gamma调试完毕!\r\n";
                    txttip.Focus();//获取焦点
                    txttip.Select(txttip.TextLength, 0);//光标定位到文本最后
                    txttip.ScrollToCaret();//滚动到光标处
                    //FirstAdjGammaFlag = true;
                    return;
                }
                if (index < PointNum)
                {
                    txttip.Text += index - 1 + "" + "完成..." + "\r\n";
                    txttip.Select(txttip.Text.Length, 0);
                    txttip.ScrollToCaret();
                    btnCalculate.PerformClick();
                    //Thread.Sleep(10); //1秒=1000毫秒，
                    //T17.Enabled = true;
                    flag1 = 1;
                    flag2 = 1;
                    flag3 = 1;
                }
                numPatternR.Value = Point_ILI7838_644[PointNum - index];
                numPatternG.Value = Point_ILI7838_644[PointNum - index];
                numPatternB.Value = Point_ILI7838_644[PointNum - index];
                if (chkBISTMode.Checked)
                {
                    btnBISTGrayShow.PerformClick();
                    Msr_CA310();
                }
                else
                {
                    OLED_Show_Click(btnPatternW, e);//写入Pattern参数
                    Msr_CA310();
                }

                //ReceivOKFlag = false;
                Thread.Sleep(20);
                T17.Enabled = true;
            }
            else
            {
                {
                    //step_l = (byte)(int.Parse(numStep.Value.ToString()));
                    switch (index)
                    {
                        //case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                        case 7:
                        case 8:
                        case 9:
                        case 10:
                        case 11:
                        case 12:
                        case 13:
                        case 14:
                        case 15:
                        case 16:
                        case 17:
                        case 18:
                        case 19:
                        case 20:
                        case 21:
                        case 22:
                        case 23:
                            {
                                if ((flag3 == 1) | (flag2 == 1) | (flag1 == 1))
                                {
                                    {//Gamma R
                                        if (lumr > D_lums[PointNum - index, 0])
                                        {
                                            if ((!lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                            if ((!lastdirupR)) { timeout++; }
                                            GVs[0, PointNum - index] = GVs[0, PointNum - index] - rstep;// (byte)(int.Parse(numStep.Value.ToString()));
                                            lastdirupR = true;
                                            // rstep = 16;
                                        }

                                        else
                                        {
                                            if ((lastdirupR) && (rstep >= 2)) rstep >>= 1;
                                            if ((lastdirupR)) { timeout++; }
                                            GVs[0, PointNum - index] = GVs[0, PointNum - index] + rstep;
                                            lastdirupR = false;
                                            //rstep = 32;
                                        }
                                        if (GVs[0, PointNum - index] < 1)
                                        {
                                            GVs[0, PointNum - index] = 1;
                                        }
                                    }

                                    {//Gamma GG
                                        {
                                            if (lumg > D_lums[PointNum - index, 1])
                                            {
                                                if ((!lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                                if ((!lastdirupG)) { timeout++; }
                                                GVs[1, PointNum - index] = GVs[1, PointNum - index] - gstep;
                                                lastdirupG = true;
                                            }
                                            else
                                            {
                                                if ((lastdirupG) && (gstep >= 2)) gstep >>= 1;
                                                if ((lastdirupG)) { timeout++; }
                                                GVs[1, PointNum - index] = GVs[1, PointNum - index] + gstep;
                                                lastdirupG = false;
                                            }
                                            if (GVs[1, PointNum - index] < 1)
                                            {
                                                GVs[1, PointNum - index] = 1;
                                            }
                                        }

                                    }

                                    {   ////Gamma BBB
                                        if (lumb > D_lums[PointNum - index, 2])
                                        {
                                            if ((!lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                            if ((!lastdirupB)) { timeout++; }
                                            GVs[2, PointNum - index] = GVs[2, PointNum - index] - bstep;
                                            lastdirupB = true;
                                        }
                                        else
                                        {
                                            if ((lastdirupB) && (bstep >= 2)) bstep >>= 1;
                                            if ((lastdirupB)) { timeout++; }
                                            GVs[2, PointNum - index] = GVs[2, PointNum - index] + bstep;
                                            lastdirupB = false;
                                        }
                                        if (GVs[2, PointNum - index] < 1)
                                        {
                                            GVs[2, PointNum - index] = 1;
                                        }
                                        txttip.Text += "rstep:" + rstep + "gstetp:" + gstep + "bstep:" + bstep + "\r\n";
                                        txttip.Select(txttip.Text.Length, 0);
                                        txttip.ScrollToCaret();
                                    }
                                }

                                CheckandCorrectGammaValue();   //检查Gamma 是否存在高低灰阶数值错乱                                

                                txtGammaValue.Text = GVs[0, PointNum - index] + "\r\n" + GVs[1, PointNum - index] + "\r\n" + GVs[2, PointNum - index] + "\r\n";

                                GValue_Format_set();  //Gamma 值与实际地址进行转换
                                if (!MainForm.comPort.IsOpen)
                                {
                                    try
                                    {
                                        MainForm.comPort.PortName = Detection.GetComNum();
                                        MainForm.comPort.BaudRate = Setting.ComSet.comBaudRate;
                                        MainForm.openSerialPort(true);
                                    }
                                    catch
                                    {
                                        MessageBox.Show("没有搜索到串口！", "错误提示");
                                        return;
                                    }
                                }
                                GammaValueSet();
                                Thread.Sleep(10);
                                Application.DoEvents();//重点，必须加上，否则父子窗体都假死                               
                            }
                            break;
                        case 24:   // PointNum - 1
                            {
                                T17.Enabled = false;
                            }
                            break;

                        default:
                            T17.Enabled = false;
                            break;
                    }
                    //System.Threading.Thread.Sleep(10);
                }
                if (!STOPGammaFlag)
                    T17.Enabled = true;
            }
        }
        bool STOPGammaFlag = false;
        private void btn_ILI7838_644_Stop_Click(object sender, EventArgs e)
        {
            T17.Stop();
            TimTest.Stop();
            btnCalculate.PerformClick();
            //GammaModeUnSet();
            STOPGammaFlag = true;
            //txtRegSend.Text = "ff,78,38,0c";
            //writeReg.PerformClick();
            //txtRegSend.Text = "e3,00";
            //writeReg.PerformClick();
        }
        private void btnSaveGamma_Click(object sender, EventArgs e)
        {
            btnCalculate.PerformClick();
            //==========
            {
                Button btnTmp = (Button)sender;
                switch (btnTmp.Name)
                {
                    case "btnSaveGamma":
                        {
                            //------------------------------------------------
                            //以文本形式保存                            
                            {//保存
                                SaveFileDialog sf = new SaveFileDialog(); //对话框
                                sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义保存的文件的类型

                                string str = "灰阶序号,灰阶亮度,reg_R,reg_G,reg_B\r\n";
                                if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                                {
                                    if (sf.FileName == "") return; //如果没有输入文件名
                                    try
                                    {
                                        StreamWriter sw = null; //文件流
                                        sw = new StreamWriter(sf.FileName, false, Encoding.UTF8);
                                        for (int i = 0; i < (this.GammaReg_dataGridView.Rows.Count - 1); i++)
                                        {
                                            str = str + this.GammaReg_dataGridView.Rows[i].Cells[0].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[1].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[2].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[3].Value.ToString() + ","
                                                + this.GammaReg_dataGridView.Rows[i].Cells[4].Value.ToString() + "\r\n";
                                        }
                                        sw.WriteLine(str);
                                        sw.Dispose(); //释放资源
                                        sw.Close(); //关闭数据流
                                        MessageBox.Show("数据保存OK！", "系统提示：");

                                    }
                                    catch
                                    {
                                        MessageBox.Show("数据保存时发生错误，请再试！", "系统提示：");
                                    }
                                }

                            }
                        }
                        break;
                    case "btnLoadGamma":
                        {
                            this.GammaReg_dataGridView.Rows.Clear();
                            OpenFileDialog sf = new OpenFileDialog();
                            int Line_Count = 0;
                            string strtmp = "";
                            sf.Filter = @"csv文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //定义文件的类型
                            sf.Title = "数据导入";
                            if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
                            {
                                FileStream fs = new FileStream(sf.FileName, FileMode.Open, FileAccess.Read);
                                StreamReader streamReader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
                                streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
                                string strLine = streamReader.ReadLine();
                                while (!string.IsNullOrEmpty(strLine))
                                {
                                    strtmp = strtmp + strLine + ",";
                                    strLine = streamReader.ReadLine(); //循环读取下一行
                                    Line_Count++;
                                }
                                fs.Close(); //关闭流
                                streamReader.Close();
                                string[] arrtmp = strtmp.Split(new Char[] { ',' });
                                for (int j = 1; j <= Line_Count - 1; j++)
                                {
                                    DataGridViewRow Row1 = new DataGridViewRow();
                                    GammaReg_dataGridView.Rows.Add(Row1);
                                }
                                try
                                {
                                    for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                                    {
                                        GammaReg_dataGridView.Rows[i].Cells[0].Value = arrtmp[5 * (i + 1) + 0];
                                        GammaReg_dataGridView.Rows[i].Cells[1].Value = arrtmp[5 * (i + 1) + 1];
                                        GammaReg_dataGridView.Rows[i].Cells[2].Value = arrtmp[5 * (i + 1) + 2];
                                        GammaReg_dataGridView.Rows[i].Cells[3].Value = arrtmp[5 * (i + 1) + 3];
                                        GammaReg_dataGridView.Rows[i].Cells[4].Value = arrtmp[5 * (i + 1) + 4];
                                        //------------------------------------
                                        GVs[0, i] = Convert.ToInt16(arrtmp[(5 * (i + 1)) + 2]);
                                        GVs[1, i] = Convert.ToInt16(arrtmp[(5 * (i + 1)) + 3]);
                                        GVs[2, i] = Convert.ToInt16(arrtmp[(5 * (i + 1)) + 4]);
                                    }
                                    MessageBox.Show("数据导入OK！", "提示：");
                                }
                                catch
                                {
                                    MessageBox.Show("数据导入时发生错误！", "提示：");
                                }
                            }
                        }
                        break;
                    case "btn_CAS200_Clean":
                        {
                            DialogResult dr = MessageBox.Show("确认清空列表数据吗？", "系统提示", MessageBoxButtons.OKCancel);
                            if (dr == DialogResult.OK)
                            {
                                this.GammaReg_dataGridView.Rows.Clear();
                            }
                        }
                        break;

                    default: break;
                }
            }
        }
        private void btnWriteGamma_Click(object sender, EventArgs e)
        {
            CheckandCorrectGammaValue();   //检查Gamma 是否存在高低灰阶数值错乱    
            GValue_Format_set();  //Gamma 值与实际地址进行转换
            GammaValueSet();
        }
        private void btnGammaValueUpdate_Click(object sender, EventArgs e)
        {
            int Line_Count = 0;
            try
            {
                Line_Count = GammaReg_dataGridView.RowCount;
            }
            catch
            {
                MessageBox.Show("表格数据(行数)异常！", "提示：");
                return;
            }
            try
            {
                for (int i = 0; i < Line_Count - 1; i++)//有一行标题
                {
                    GVs[0, i] = Convert.ToInt16(GammaReg_dataGridView.Rows[i].Cells[2].Value);
                    GVs[1, i] = Convert.ToInt16(GammaReg_dataGridView.Rows[i].Cells[3].Value);
                    GVs[2, i] = Convert.ToInt16(GammaReg_dataGridView.Rows[i].Cells[4].Value);
                }
                //MessageBox.Show("数据更新OK！", "提示：");
                txttip.Text += "Gamma数据更新OK！\r\n";
                btnWriteGamma.PerformClick();
            }
            catch
            {
                MessageBox.Show("Gamma数据更新错误！", "唐韬说：");
            }
        }
        private void btnCalculate_Click(object sender, EventArgs e)
        {
            D_lum = new double[PointNum];
            {
                this.GammaReg_dataGridView.Rows.Clear();
            }

            for (byte i = 0; i < PointNum; i++)
            {
                D_lum[i] = (Math.Pow((Point_ILI7838_644[i] / 255.0), Convert.ToDouble(txtVT_gamma.Text)) * Convert.ToDouble(txtVT_lum.Text));
                DataGirdShow(i, GVs[0, i], GVs[1, i], GVs[2, i]);
            }
        }
        public void DataGirdShow(byte index, double RRR, double GGG, double BBB)
        {
            int Row_Accum = 0, Current_Index = 0, Row_flag = 0;

            DataGridViewRow Row1 = new DataGridViewRow();

            Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
            if (Row_Accum != 0)
            {
                Current_Index = this.GammaReg_dataGridView.SelectedCells[0].RowIndex;
                if ((Current_Index != Row_Accum - 1) && (Current_Index != Row_Accum))
                {
                    Row_Accum = Current_Index;
                    Row_flag = 1;
                }
                else
                {
                    this.GammaReg_dataGridView.Rows.Add(Row1);
                }
                if ((Row_Accum != 0) && (Row_flag != 1))
                {
                    if (Current_Index != Row_Accum)
                    {
                        this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = false;
                        this.GammaReg_dataGridView.Rows[Row_Accum].Selected = true;
                    }
                }
            }
            else
            {
                this.GammaReg_dataGridView.Rows.Add(Row1);
            }
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[0].Value = index + 1;//序号
            //Rows[x]为第x行,Cells[x]为第x列
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[1].Value = (D_lum[index]).ToString("#0.0000");
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[2].Value = RRR;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[3].Value = GGG;
            this.GammaReg_dataGridView.Rows[Row_Accum].Cells[4].Value = BBB;

            if (Row_flag == 1)
            {
                Row_flag = 0;
                Row_Accum = this.GammaReg_dataGridView.Rows.Count - 1;
                this.GammaReg_dataGridView.Rows[Current_Index].Selected = false;
                this.GammaReg_dataGridView.Rows[Row_Accum - 1].Selected = true;
            }
            GammaReg_dataGridView.FirstDisplayedScrollingRowIndex = GammaReg_dataGridView.RowCount - 1;
        }
        private void ILI8818_GammaWR_All_Click(object sender, EventArgs e)
        {

            btnCalculate.PerformClick();
        }
        private void ILI8818_GammaWR_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            Send_buf = new byte[54];
            Setting.TempRecord.cmdLen = 54;//
            Send_buf[0] = 0x6F; //ILI8818
            Send_buf[2] = 49;//0x31  CRC校验-2，-1了
            //----------Gamma段切换-------------
            //if (rbt_ILI8818_Normal_1.Checked == true) { Send_buf[3] = 0x00; txt_Reg_Data_WR.Text = "FF,78,38,20"; }
            ////else if (rbt_ILI8818_Normal_2.Checked == true) { Send_buf[3] = 0x01; txt_Reg_Data_WR.Text = "FF,78,38,0A"; }
            ////else if (rbt_ILI8818_Normal_3.Checked == true) { Send_buf[3] = 0x02; txt_Reg_Data_WR.Text = "FF,78,38,0B"; }
            ////else if (rbt_ILI8818_Normal_4.Checked == true) { Send_buf[3] = 0x03; txt_Reg_Data_WR.Text = "FF,78,38,0C"; }
            //else if (rbt_ILI8818_HBM.Checked == true) { Send_buf[3] = 0x04; txt_Reg_Data_WR.Text = "FF,78,38,1E"; }//E
            //else if (rbt_ILI8818_AOD.Checked == true) { Send_buf[3] = 0x05; txt_Reg_Data_WR.Text = "FF,78,38,2B"; }//F
            //----------------------------------------------------------------------------------
            switch (btnTmp.Name)
            {
                //-----------------------------------------------------------------------
                case "btn_ILI8818_GammaR_RED":// 0x6F,0x09,0x49,0x10
                    {
                        Setting.TempRecord.ILI8818_GammaCmdType = 0x03;
                        Send_buf[1] = 0x09;
                        Send_buf[3] |= 0x10;
                    }
                    break;
                case "btn_ILI8818_GammaR_GREEN":
                    {
                        Setting.TempRecord.ILI8818_GammaCmdType = 0x04;
                        Send_buf[1] = 0x09;
                        Send_buf[3] |= 0x20;
                    }
                    break;
                case "btn_ILI8818_GammaR_BLUE":
                    {
                        Setting.TempRecord.ILI8818_GammaCmdType = 0x05;
                        Send_buf[1] = 0x09;
                        Send_buf[3] |= 0x30;
                    }
                    break;
            }
            CRCData.CalculateCrc16(Send_buf, out Send_buf[Setting.TempRecord.cmdLen - 2], out Send_buf[Setting.TempRecord.cmdLen - 1]);
            try
            {
                MainForm.comPort.Write(Send_buf, 0, Setting.TempRecord.cmdLen);   //
                Page0Set();
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
            }
            MainForm.T1.Enabled = false;
            MainForm.T1.Interval = 2000;
            MainForm.T1.Enabled = true;
        }
        #endregion
        #region //通用命令处理
        private void Send_Cmd_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            switch (btn.Name)
            {
                case "btnSend1":
                    {
                        MainForm.txtProcessDrivercode(txtCmd1.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend2":
                    {
                        MainForm.txtProcessDrivercode(txtCmd2.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;
                case "btnSend3":
                    {
                        MainForm.txtProcessDrivercode(txtCmd3.Text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                    }
                    break;

            }
            Setting.TempRecord.cmdLen = 6;
            if (rBt_LP_DCS_Long_Write.Checked | rBt_LP_DCS_Short_Write.Checked | rBt_LP_Gerneric_Long_Write.Checked | rBt_LP_Gerneric_Short_Write.Checked)
            {
                MainForm.SendCmd(0);
            }
            else
            {
                MainForm.SendCmd(4);
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }
        private void SaveCode_Click(object sender, EventArgs e)
        {
            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            string str = "//-----保存Driver IC Code文件------\r\n";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    if (ChkCMD1.Checked)
                    {
                        str += "//---CMD1---\r\n" + txtCmd1.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD2.Checked)
                    {
                        str += "//---CMD2---\r\n" + txtCmd2.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    if (ChkCMD3.Checked)
                    {
                        str += "//---CMD3---\r\n" + txtCmd3.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n\r\n";
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    MessageBox.Show("Driver IC Code保存OK！", "系统提示：");
                }
                catch
                {
                    MessageBox.Show("Driver IC Code保存时发生错误，请再试！", "系统提示：");
                }
            }
        }
        private void OpenTxtCode_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            OpenFileDialog of = new OpenFileDialog();
            of.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            of.Title = "初始化 Code";

            if (of.ShowDialog() == DialogResult.OK)
            {
                StreamReader streamReader = new StreamReader(of.FileName, Encoding.Default);
                switch (btn.Name)
                {
                    case "OpenTxtCode":
                        {
                            txtCmd1.Clear();
                            txtCmd1.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode2":
                        {
                            txtCmd2.Clear();
                            txtCmd2.Text = streamReader.ReadToEnd();
                        }
                        break;
                    case "OpenTxtCode3":
                        {
                            txtCmd3.Clear();
                            txtCmd3.Text = streamReader.ReadToEnd();
                        }
                        break;

                    default: break;
                }
                streamReader.Close();
            }
        }
        #endregion

        private void btnCleartiptxt_Click(object sender, EventArgs e)
        {
            txttip.Clear();
        }

        private void btnResetOled_Click(object sender, EventArgs e)
        {
            MainForm.btnRun_Click(MainForm.btnRun, e);
        }

        #region //------自定义功能按键---------------
        private void CustomSendCmd_Click(object sender, EventArgs e)   //自定义功能按键
        {
            Button btn = (Button)sender; string spedflag = "";
            switch (btn.Name)
            {
                case "btnFun1":
                    {
                        MainForm.txtProcessDrivercode(funcmd1, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag1;
                    }
                    break;
                case "btnFun2":
                    {
                        MainForm.txtProcessDrivercode(funcmd2, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag2;
                    }
                    break;
                case "btnFun3":
                    {
                        MainForm.txtProcessDrivercode(funcmd3, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag3;
                    }
                    break;
                case "btnFun4":
                    {
                        MainForm.txtProcessDrivercode(funcmd4, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag4;
                    }
                    break;
                case "btnFun5":
                    {
                        MainForm.txtProcessDrivercode(funcmd5, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag5;
                    }
                    break;
                case "btnFun6":
                    {
                        MainForm.txtProcessDrivercode(funcmd6, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag6;
                    }
                    break;
                case "btnFun7":
                    {
                        MainForm.txtProcessDrivercode(funcmd7, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag7;
                    }
                    break;
                case "btnFun8":
                    {
                        MainForm.txtProcessDrivercode(funcmd8, out string txtbaseClearOriginal, out string txtMCleatOriginal);
                        spedflag = speedflag8;
                    }
                    break;

            }
            //Setting.TempRecord.cmdLen = 6;
            if (spedflag == "LP")
            {
                MainForm.SendCmd(0);  //低速
            }
            else
            {
                MainForm.SendCmd(4); //高速
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }

        string path = "";
        string FunDefaultfilePath = "";
        string funcmd1, funcmd2, funcmd3, funcmd4, funcmd5, funcmd6, funcmd7, funcmd8;

        private void btnFunTestcmdSaveAS_Click(object sender, EventArgs e)
        {
            string tfilname = "ILI7838_644Fun1.txt";
            if (rdoFun1.Checked) { tfilname = "ILI7838_644Fun1.txt"; }
            else if (rdoFun2.Checked) { tfilname = "ILI7838_644Fun2.txt"; }
            else if (rdoFun3.Checked) { tfilname = "ILI7838_644Fun3.txt"; }
            else if (rdoFun4.Checked) { tfilname = "ILI7838_644Fun4.txt"; }
            else if (rdoFun5.Checked) { tfilname = "ILI7838_644Fun5.txt"; }
            else if (rdoFun6.Checked) { tfilname = "ILI7838_644Fun6.txt"; }
            else if (rdoFun7.Checked) { tfilname = "ILI7838_644Fun7.txt"; }
            else if (rdoFun8.Checked) { tfilname = "ILI7838_644Fun8.txt"; }

            SaveFileDialog txt = new SaveFileDialog();
            txt.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            txt.FileName = tfilname;
            string str = "";
            if (txt.ShowDialog() == DialogResult.OK)
            {
                if (txt.FileName == " ")
                {
                    return;
                }
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(txt.FileName, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                try
                {
                    {
                        str += txtFuncmd.Text;// lstMIPIDriver.Items[i].ToString();
                        str += "\r\n";
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流
                    //MessageBox.Show("自定义命令保存OK，但请确认文件名是否规范！", "系统提示：");
                    txttip.Text += tfilname + "命令导出保存OK，请确认文件名！" + "\r\n";
                    txttip.Select(txttip.Text.Length, 0);
                    txttip.ScrollToCaret();
                }
                catch
                {
                    MessageBox.Show("保存时发生错误，请再试！", "系统提示：");
                }
            }
        }

        private void btnFunEdit_Click(object sender, EventArgs e)
        {
            string tfilname = "ILI7838_644Fun1.cfg";
            if (rdoFun1.Checked) { tfilname = "ILI7838_644Fun1.cfg"; }
            else if (rdoFun2.Checked) { tfilname = "ILI7838_644Fun2.cfg"; }
            else if (rdoFun3.Checked) { tfilname = "ILI7838_644Fun3.cfg"; }
            else if (rdoFun4.Checked) { tfilname = "ILI7838_644Fun4.cfg"; }
            else if (rdoFun5.Checked) { tfilname = "ILI7838_644Fun5.cfg"; }
            else if (rdoFun6.Checked) { tfilname = "ILI7838_644Fun6.cfg"; }
            else if (rdoFun7.Checked) { tfilname = "ILI7838_644Fun7.cfg"; }
            else if (rdoFun8.Checked) { tfilname = "ILI7838_644Fun8.cfg"; }
            else { MessageBox.Show("未指定按键"); return; }
            try
            {
                StreamReader streamReader = new StreamReader((Application.StartupPath + "\\x_ILITEK\\" + tfilname), Encoding.Default);
                txtFuncmd.Text = streamReader.ReadToEnd();
                streamReader.Dispose();
                streamReader.Close();
            }
            catch
            {
                MessageBox.Show("保存命令时发生错误，请再试！", "系统提示：");
            }
        }

        private void btnPreproccess_Click(object sender, EventArgs e)
        {
            string acmd = "";
            acmd = txtFuncmd.Text;
            acmd = acmd.Replace("0x", "");
            acmd = acmd.Replace("0X", "");
            acmd = acmd.Replace("REGW", "");
            acmd = acmd.Replace("regw", "");
            txtFuncmd.Text = acmd;

            string str = "";
            foreach (string s2 in txtFuncmd.Lines)
            {
                if (s2 == "")
                {
                    continue;
                }
                str += s2.Trim() + "\r\n";
            }
            txtFuncmd.Text = str;
        }

        private void btnBISTGrayShow_Click(object sender, EventArgs e)
        {
            byte[] TepArr;
            byte GrayLevel;
            byte GrayLevel_1, GrayLevel_2;
            byte bgray = 255;
            TepArr = new byte[] { 1, 2, 3 };
            if (chkAODGamma.Checked)
            {
                bgray = byte.Parse(numPatternR.Value.ToString());
                if (chkAODGamma.Checked)
                {
                    TepArr = new byte[] { 
                // 先通过bist模式送AOD 图
                //切Page >> 2
                4,0xff,0x78,0x38,0x02,
                4,0xff,0xff,0xff,0x1f,
                2,0x1b,0x04,  //data shift 关闭， 120Hz时导致ip工作时间不够，显示异常，故120Hz初始化时开启了datashift功能
                2,0x88,0x00,    // Set BIST pattern FRM_PT[10] and disable other pattern
                2,0x89,0x04,
                2,0x8a,0x00,

                2,0x8e,0x63,    // Set BOX Y-axis location & height 704 lines
                2,0x8f,0xc6,
                2,0x90,0x86,
                2,0x91,0x00,    // 0  BOX_X2[10:8]  BOX_BIST_SEL  BOX_X1[10:8]
                2,0x92,0x42,    //x1, 7:0
                2,0x93,0xf3,    //y1, 7:0

                2,0xa2,0x80,    // Box modulation enable               
                2,0xa5,0x01,    // BIST Mode enable free run

                2,0x9a,(byte)((bgray>>6)+((bgray&0xc0)>>4)+((bgray&0xc0)>>2)),    // Set BOX in black & pixel value = W255 (Octal)
                2,0x9b,(byte)((bgray<<2)),
                2,0x9c,(byte)((bgray<<2)),
                2,0x9d,(byte)((bgray<<2)),

                 4,0xff,0x78,0x38,0x00, //page 0
                4,0xff,0xff,0xff,0x1f,
                1,0x39
                       };
                }
            }
            else
            {
                GrayLevel = byte.Parse(numPatternR.Value.ToString());
                GrayLevel_1 = (byte)((GrayLevel >> 1) & 0x60 + 4);
                GrayLevel_2 = (byte)((GrayLevel << 2) & 0xFC);

                TepArr = new byte[] {
                        4,0xff,0x78,0x38,0x02,
                        2,0x1b,0x04,  //data shift 关闭， 120Hz时导致ip工作时间不够，显示异常，故120Hz初始化时开启了datashift功能
                        2,0xa2,0x00,
                        2,0x88,0x00,
                        2,0x89,0x00,
                        2,0x8a,0x10,
                        2,0x8b,0x00,
                        2,0x8c, GrayLevel_1 ,
                        2,0x8d, GrayLevel_2 ,
                        2,0xa5,0x01,
                       };
            }
            try
            {
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
            if (chkLvTest.Checked)
            {
                Msr_CA310();
                txttip.Text = "当前亮度：" + auto_lum + "\r\n";
            }
        }

        private void btnBISTAllColorShow_Click(object sender, EventArgs e)
        {
            Button btnTmp = (Button)sender;
            byte[] TepArr;
            byte GrayLevel = 1; //white

            switch (btnTmp.Name)
            {
                case "btnred":
                    {
                        GrayLevel = 4;  //red
                        txttip.Text += "---R---" + "\r\n";
                    }
                    break;
                case "btngreen":
                    {
                        GrayLevel = 8;  //green
                        txttip.Text += "---G---" + "\r\n";
                        break;
                    }
                case "btnblue":
                    {
                        GrayLevel = 0x10;
                        txttip.Text += "---B---" + "\r\n";
                        break;
                    }
                case "btnwhite":
                    {
                        GrayLevel = 1;  //
                        txttip.Text += "---WHITE---" + "\r\n";
                    }
                    break;
                case "btnblack":
                    {
                        GrayLevel = 2;  //
                        txttip.Text += "---BLACK---" + "\r\n";
                    }
                    break;

                default: break;
            }

            TepArr = new byte[] {
                        4,0xff,0x78,0x38,0x02,
                        //2,0xa2,0x00,
                        2,0x88, GrayLevel,
                        2,0x89,0x00,
                        2,0x8a,0x00,

                        2,0x8c, 00 ,    //// SET FRAME DURATION 64 FRAME ~ 1S                       
                        2,0xa5,0x01,  // // BIST MODE ENABLE
                       };
            try
            {
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }

        private void chkBISTMode_CheckedChanged(object sender, EventArgs e)
        {
            if (!chkBISTMode.Checked)
            {
                byte[] TepArr;


                TepArr = new byte[] {
                        4,0xff,0x78,0x38,0x02,
                        2,0xa5,0x00,  // // BIST MODE DISABLE
                        4,0xff,0x78,0x38,0x00
                       };
                try
                {
                    MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
                }
                catch
                {
                    MessageBox.Show("串口有误，请检查", "错误");
                    return;
                }
            }

        }

        private void numStep_ValueChanged(object sender, EventArgs e)
        {
            rstep = (byte)(int.Parse(numStep.Value.ToString()));
            gstep = (byte)(int.Parse(numStep.Value.ToString()));
            bstep = (byte)(int.Parse(numStep.Value.ToString()));
        }

        private void rdo60Hz_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            if (rb != null)
            {
                if (rb.Checked)
                {
                    // Only one radio button will be checked
                    Console.WriteLine("Changed: " + rb.Name);
                }
            }
            groupGamma_Parameter.Enabled = true;
            groupAutoGamma.Enabled = true;
            if (rdo120Hz.Checked)
            {
                GFrame = 0x31;
                if (rdo_ILI8818_Normal_1.Checked)
                {
                    Gpage = 0x20;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 800; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,0F,FF";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_2.Checked)
                {
                    Gpage = 0x21;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 500; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,0D,BB";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_3.Checked)
                {
                    Gpage = 0x22;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 300; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,09,85";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_4.Checked)
                {
                    Gpage = 0x23;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 90; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,05,03";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_5.Checked)
                {
                    Gpage = 0x24;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 30; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,02,BD";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_6.Checked)
                {
                    Gpage = 0x25;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 10; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,01,6C";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_7.Checked)
                {
                    Gpage = 0x26;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 5; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,00,DA";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_8.Checked)
                {
                    Gpage = 0x27;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 2; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,00,01";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rbt_ILI8818_HBM.Checked)
                {
                    Gpage = 0x1E;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 800; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,0F,FF";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
            }
            else if (rdo90Hz.Checked)
            {
                GFrame = 0x32;
                if (rdo_ILI8818_Normal_1.Checked)
                {
                    Gpage = 0x2B;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 800; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,0F,FF";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_2.Checked)
                {
                    Gpage = 0x2C;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 500; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,0D,BB";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_3.Checked)
                {
                    Gpage = 0x2D;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 300; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,09,85";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_4.Checked)
                {
                    Gpage = 0x2E;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 90; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,05,03";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_5.Checked)
                {
                    Gpage = 0x2F;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 30; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,02,BD";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_6.Checked)
                {
                    Gpage = 0x30;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 10; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,01,6C";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_7.Checked)
                {
                    Gpage = 0x31;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 5; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,00,DA";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_8.Checked)
                {
                    Gpage = 0x32;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 2; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,00,01";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rbt_ILI8818_HBM.Checked)
                {
                    Gpage = 0x29;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 800; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,0F,FF";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
            }
            else  // 60Hz
            {
                GFrame = 0x33;
                if (rdo_ILI8818_Normal_1.Checked)
                {
                    Gpage = 0x36;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 800; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,0F,FF";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_2.Checked)
                {
                    Gpage = 0x37;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 500; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,0D,BB";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_3.Checked)
                {
                    Gpage = 0x38;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 300; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,09,85";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_4.Checked)
                {
                    Gpage = 0x39;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 90; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,05,03";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_5.Checked)
                {
                    Gpage = 0x3A;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 30; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,02,BD";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_6.Checked)
                {
                    Gpage = 0x3B;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 10; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,01,6C";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_7.Checked)
                {
                    Gpage = 0x3C;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 5; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,00,DA";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rdo_ILI8818_Normal_8.Checked)
                {
                    Gpage = 0x3D;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 2; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,00,01";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
                else if (rbt_ILI8818_HBM.Checked)
                {
                    Gpage = 0x34;
                    if (chkAutoDBV.Checked) { txtVT_lum.Text = "" + 800; }
                    txtRegSend.Text = "ff,78,38,00";
                    writeReg.PerformClick();
                    txtRegSend.Text = "51,0F,FF";
                    if (chkAuto51set.Checked) { writeReg.PerformClick(); }
                }
            }
            numGammaPage.Value = Gpage;
        }

        private void chkAODGamma_CheckedChanged(object sender, EventArgs e)
        {
            byte[] TepArr;
            TepArr = new byte[] { 1, 2 };
            //byte bgray = 255;
            //bgray= byte.Parse(numPatternR.Value.ToString());
            if (chkAODGamma.Checked)
            {
                //TepArr = new byte[] { 
                //// 先通过bist模式送AOD 图
                ////切Page >> 2
                //4,0xff,0x78,0x38,0x02,
                //4,0xff,0xff,0xff,0x1f,
                //2,0x88,0x00,    // Set BIST pattern FRM_PT[10] and disable other pattern
                //2,0x89,0x04,
                //2,0x8a,0x00,

                //2,0x8e,0x63,    // Set BOX Y-axis location & height 704 lines
                //2,0x8f,0xc6,
                //2,0x90,0x86,
                //2,0x91,0x00,    // 0  BOX_X2[10:8]  BOX_BIST_SEL  BOX_X1[10:8]
                //2,0x92,0x42,    //x1, 7:0
                //2,0x93,0xf3,    //y1, 7:0

                //2,0xa2,0x80,    // Box modulation enable               
                //2,0xa5,0x01,    // BIST Mode enable free run

                //2,0x9a,(byte)((bgray>>6)+((bgray&0xc0)>>4)+((bgray&0xc0)>>2)),    // Set BOX in black & pixel value = W255 (Octal)
                //2,0x9b,(byte)((bgray<<2)),
                //2,0x9c,(byte)((bgray<<2)),
                //2,0x9d,(byte)((bgray<<2)),

                // 4,0xff,0x78,0x38,0x00, //page 0
                //4,0xff,0xff,0xff,0x1f,
                //1,0x39
                //       };
            }
            else
            {
                TepArr = new byte[] {
                 4,0xff,0x78,0x38,0x00, //page 0
                4,0xff,0xff,0xff,0x1f,
                1,0x38
                       };
            }
            try
            {
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }

        private void btnEnterHBM_Click(object sender, EventArgs e)
        {
            if (btnEnterHBM.Tag == null)
            {
                btnEnterHBM.Tag = 1;
                txtRegSend.Text = "53,e0";
                writeReg.PerformClick();
                labHBM.Text = "ON";
                Application.DoEvents();
            }
            else
            {
                txtRegSend.Text = "53,20";
                btnEnterHBM.Tag = null;
                writeReg.PerformClick();
                labHBM.Text = "OFF";
                Application.DoEvents();
            }

        }

        private void cbx_BISTPattern_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Button btnTmp = (Button)sender;
            byte[] TepArr;
            Int32 FRM_PT = 1; //white
            FRM_PT = (cbx_BISTPattern.SelectedIndex + 5);
            FRM_PT = (1 << FRM_PT);
            TepArr = new byte[] {
                        4,0xff,0x78,0x38,0x02,
                        //2,0xa2,0x00,
                        2,0x88, (byte)(FRM_PT&0xff),
                        2,0x89, (byte)((FRM_PT>>8)&0xff),
                        2,0x8a, (byte)((FRM_PT>>16)&0xff),

                        2,0x8c, 00 ,    //// SET FRAME DURATION 64 FRAME ~ 1S                       
                        2,0xa5,0x01,  // // BIST MODE ENABLE
                       };
            try
            {
                MainForm.comPort.Write(GetCRCArray(TepArr, 4), 0, TepArr.Length + 6);//循环部分，每段数据结尾                  
            }
            catch
            {
                MessageBox.Show("串口有误，请检查", "错误");
                return;
            }
        }

        private void btnFunexport_Click(object sender, EventArgs e)
        {
            rdoFun1.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun2.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun3.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun4.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun5.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun6.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun7.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
            rdoFun8.Checked = true;
            btnFunEdit.PerformClick();
            btnFunTestcmdSaveAS.PerformClick();
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            path = Application.StartupPath + "\\x_ILITEK"; txttip.Text += path + "";
            try
            {
                //StreamReader streamReader = new StreamReader(path+"\\Fun1.txt", Encoding.Default);
                //FunDefaultfilePath = streamReader.ReadLine();
                //streamReader.Close();
                ReadFuncfg(path + "\\ILI7838_644Fun1.cfg", out String Ftitle1, out speedflag1, out funcmd1);
                btnFun1.Text = Ftitle1;

                ReadFuncfg(path + "\\ILI7838_644Fun2.cfg", out String Ftitle2, out speedflag2, out funcmd2);
                btnFun2.Text = Ftitle2;

                ReadFuncfg(path + "\\ILI7838_644Fun3.cfg", out String Ftitle3, out speedflag3, out funcmd3);
                btnFun3.Text = Ftitle3;

                ReadFuncfg(path + "\\ILI7838_644Fun4.cfg", out String Ftitle4, out speedflag4, out funcmd4);
                btnFun4.Text = Ftitle4;

                ReadFuncfg(path + "\\ILI7838_644Fun5.cfg", out String Ftitle5, out speedflag5, out funcmd5);
                btnFun5.Text = Ftitle5;

                ReadFuncfg(path + "\\ILI7838_644Fun6.cfg", out String Ftitle6, out speedflag6, out funcmd6);
                btnFun6.Text = Ftitle6;

                ReadFuncfg(path + "\\ILI7838_644Fun7.cfg", out String Ftitle7, out speedflag7, out funcmd7);
                btnFun7.Text = Ftitle7;

                ReadFuncfg(path + "\\ILI7838_644Fun8.cfg", out String Ftitle8, out speedflag8, out funcmd8);
                btnFun8.Text = Ftitle8;
                //btnStore.Enabled = true;
                txttip.Text += "按键功能刷新完成" + "\r\n";
                //MessageBox.Show("刷新完成", "向东说");
            }
            catch
            {
                MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
        }
        private void btnStore_Click(object sender, EventArgs e)
        {
            string str = "";
            {
                try
                {
                    StreamWriter sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ILITEK\\ILI7838_644Fun1.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun1.Text + "\r\n";//
                        str += speedflag1 + "\r\n";
                        str += funcmd1;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ILITEK\\ILI7838_644Fun2.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun2.Text + "\r\n";//
                        str += speedflag2 + "\r\n";
                        str += funcmd2;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ILITEK\\ILI7838_644Fun3.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun3.Text + "\r\n";//
                        str += speedflag3 + "\r\n";
                        str += funcmd3;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ILITEK\\ILI7838_644Fun4.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun4.Text + "\r\n";//
                        str += speedflag4 + "\r\n";
                        str += funcmd4;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ILITEK\\ILI7838_644Fun5.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun5.Text + "\r\n";//
                        str += speedflag5 + "\r\n";
                        str += funcmd5;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ILITEK\\ILI7838_644Fun6.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun6.Text + "\r\n";//
                        str += speedflag6 + "\r\n";
                        str += funcmd6;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ILITEK\\ILI7838_644Fun7.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun7.Text + "\r\n";//
                        str += speedflag7 + "\r\n";
                        str += funcmd7;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    str = ""; sw = null; //文件流
                    sw = new StreamWriter(Application.StartupPath + "\\x_ILITEK\\ILI7838_644Fun8.cfg", false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")
                    {
                        str += btnFun8.Text + "\r\n";//
                        str += speedflag8 + "\r\n";
                        str += funcmd8;
                    }
                    sw.Write(str);
                    sw.Dispose(); //释放资源
                    sw.Close(); //关闭数据流

                    MessageBox.Show("向东说固化命令成功！", "系统提示：");
                    btnRefresh.Enabled = true;
                    btnStore.Enabled = false;
                }
                catch
                {
                    MessageBox.Show("固化命令时发生错误，请再试！", "系统提示：");
                }
            }
        }
        private void btnFunTestcmdSend_Click(object sender, EventArgs e)
        {
            if (chkFunpreproccess.Checked) { btnPreproccess.PerformClick(); }
            String[] lines = txtFuncmd.Text.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            string speedflag = lines[1];
            String text = "";
            for (int i = 0; i < lines.Length; i++)
            {
                //假设删除第2行第3行
                if (i == 0 || i == 1)
                {
                    continue;
                }
                text += lines[i] + (i == lines.Length - 1 ? "" : "\r\n"); //最后一行不添加换行符
            }
            MainForm.txtProcessDrivercode(text, out string txtbaseClearOriginal, out string txtMCleatOriginal);
            if (speedflag == "LP")
            {
                MainForm.SendCmd(0);  //低速
            }
            else
            {
                MainForm.SendCmd(4); //高速
            }
            txttip.Text += "命令已下发...\r\n";
            txttip.Select(txttip.Text.Length, 0);
            txttip.ScrollToCaret();
        }
        private void btnFunTestcmdSave_Click(object sender, EventArgs e)
        {
            string str = "";
            string tpath = Application.StartupPath + "\\x_ILITEK";
            string tfilname = "ILI7838_644Fun1.cfg";
            if (rdoFun1.Checked) { tfilname = "ILI7838_644Fun1.cfg"; }
            else if (rdoFun2.Checked) { tfilname = "ILI7838_644Fun2.cfg"; }
            else if (rdoFun3.Checked) { tfilname = "ILI7838_644Fun3.cfg"; }
            else if (rdoFun4.Checked) { tfilname = "ILI7838_644Fun4.cfg"; }
            else if (rdoFun5.Checked) { tfilname = "ILI7838_644Fun5.cfg"; }
            else if (rdoFun6.Checked) { tfilname = "ILI7838_644Fun6.cfg"; }
            else if (rdoFun7.Checked) { tfilname = "ILI7838_644Fun7.cfg"; }
            else if (rdoFun8.Checked) { tfilname = "ILI7838_644Fun8.cfg"; }
            else { MessageBox.Show("未指定按键"); return; }
            try
            {
                StreamWriter sw = null; //文件流
                sw = new StreamWriter(Application.StartupPath + "\\x_ILITEK\\" + tfilname, false, Encoding.GetEncoding("UTF-8"));//Encoding.GetEncoding("UTF-8")

                {
                    str = txtFuncmd.Text;
                }
                sw.Write(str);
                sw.Dispose(); //释放资源
                sw.Close(); //关闭数据流
                            // MessageBox.Show("自定义命令保存OK，但请确认文件名是否规范！", "系统提示：");

                MessageBox.Show(tfilname + "保存命令成功！", "向东说：");
                btnRefresh.Enabled = true;
                btnStore.Enabled = false;
                btnRefresh.PerformClick();
            }
            catch
            {
                MessageBox.Show("保存命令时发生错误，请再试！", "系统提示：");
            }
        }
        string speedflag1, speedflag2, speedflag3, speedflag4, speedflag5, speedflag6, speedflag7, speedflag8;
        private void btnFunLoad_Click(object sender, EventArgs e)
        {
            int num = 0;
            {
                StreamReader streamReader = new StreamReader("./update/Fun.cfg", Encoding.Default);
                FunDefaultfilePath = streamReader.ReadLine();
                streamReader.Close();
            }
            FolderBrowserDialog fldb = new FolderBrowserDialog();
            //首次defaultfilePath为空，按FolderBrowserDialog默认设置（即桌面）选择            
            if (FunDefaultfilePath != "")
            {
                //设置此次默认目录为上一次选中目录
                fldb.SelectedPath = FunDefaultfilePath;
            }

            fldb.ShowNewFolderButton = false;
            DialogResult res = fldb.ShowDialog();
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                MessageBox.Show("没选择任何文件夹.");
                return;
            }
            FunDefaultfilePath = fldb.SelectedPath;
            path = fldb.SelectedPath;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("文件夹不存在.");
                return;
            }

            StreamWriter sw = null; //文件流
            sw = new StreamWriter("./update/Fun.cfg", false, Encoding.Default);//Encoding.GetEncoding("UTF-8")
            sw.Write(FunDefaultfilePath);
            sw.Dispose(); //释放资源
            sw.Close(); //关闭数据流
            // -------------------------------------------------------------------------
            try
            {
                ReadFuncfg(path + "\\ILI7838_644Fun1.txt", out String Ftitle1, out speedflag1, out funcmd1);
                btnFun1.Text = Ftitle1; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\ILI7838_644Fun2.txt", out String Ftitle2, out speedflag2, out funcmd2);
                btnFun2.Text = Ftitle2; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\ILI7838_644Fun3.txt", out String Ftitle3, out speedflag3, out funcmd3);
                btnFun3.Text = Ftitle3; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\ILI7838_644Fun4.txt", out String Ftitle4, out speedflag4, out funcmd4);
                btnFun4.Text = Ftitle4; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\ILI7838_644Fun5.txt", out String Ftitle5, out speedflag5, out funcmd5);
                btnFun5.Text = Ftitle5; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\ILI7838_644Fun6.txt", out String Ftitle6, out speedflag6, out funcmd6);
                btnFun6.Text = Ftitle6; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\ILI7838_644Fun7.txt", out String Ftitle7, out speedflag7, out funcmd7);
                btnFun7.Text = Ftitle7; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            try
            {
                ReadFuncfg(path + "\\ILI7838_644Fun8.txt", out String Ftitle8, out speedflag8, out funcmd8);
                btnFun8.Text = Ftitle8; num++;
            }
            catch
            {
                //MessageBox.Show("配置文件缺失，请检查", "向东提示");
            }
            btnStore.Enabled = true;
            if (num < 8)
            {
                MessageBox.Show("完成" + num + "个配置，部分按键配置文件缺失，请检查", "向东提示");
            }

        }
        private void ReadFuncfg(string addr, out String Ftitle, out String speedflag, out String Fcmd)
        {
            lines = new List<string>();

            //FileStream fs = new FileStream(Application.StartupPath + "\\x_ILITEK\\ILI7838_644Fun1.txt", FileMode.Open)
            FileStream fs = new FileStream(addr, FileMode.Open);
            StreamReader rd = new StreamReader(fs);
            string s;
            //读入文件所有行，存放到List<string>集合中
            while ((s = rd.ReadLine()) != null)
            {
                lines.Add(s);
            }
            rd.Close();
            fs.Close();
            //第一行在txttip中显示
            Ftitle = "";
            speedflag = "";
            if (lines.Count > 0)
            {
                Ftitle = lines[0];
                speedflag = lines[1];
            }
            //txtFuncmd.Text = "";
            Fcmd = "";
            for (int i = 2; i < lines.Count; i++)
            {
                Fcmd += lines[i] + "\r\n";
            }

        }
        #endregion
        static byte[] GetCRCArray(byte[] arr, Byte speedflag)
        {
            CRC16 CRCData = new CRC16();

            int arrNumbuer;                                                                                                                                                                                                                                                                                                                                             //51
            arrNumbuer = arr.Length;
            arrNumbuer += 6;
            byte[] Send_Datax = new byte[arrNumbuer];
            Send_Datax[0] = 0x9f;
            Send_Datax[1] = (byte)(speedflag << 4);
            Send_Datax[2] = Convert.ToByte(arr.Length + 1);  //为兼容下位机命令，此位置填待传输有效数据长度+1 

            Send_Datax[arr.Length + 3] = 0xFF;  //添加结束标志位
            arr.CopyTo(Send_Datax, 3);//合并数组头 4个Byte 标志位
            //计算校验码                                                 
            CRCData.CalculateCrc16(Send_Datax, out Send_Datax[arrNumbuer - 2], out Send_Datax[arrNumbuer - 1]);
            return Send_Datax;
        }

        private void T5_Tick(object sender, EventArgs e)
        {
        }



    }
}
